Coverage for src/python/ensembl/vep/corpus/registry.py: 100%
49 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Corpus factories and their registry."""
16from __future__ import annotations
18from collections.abc import Callable
20from ensembl.vep.corpus.base import Corpus
21from ensembl.vep.corpus.spec import CorpusSpec
23__all__ = [
24 "CorpusFactory",
25 "CorpusOptionsError",
26 "available_corpora",
27 "build_corpus",
28 "build_corpus_from_options",
29 "corpus_factory",
30 "corpus_spec_from_options",
31 "register_corpus",
32]
35class CorpusOptionsError(ValueError):
36 """A configured corpus name, parameter, or external input cannot be used."""
39CorpusFactory = Callable[[CorpusSpec], Corpus]
40"""Build a corpus from its specification."""
42_CORPUS_FACTORIES: dict[str, CorpusFactory] = {}
43_CORPUS_ALIASES: dict[str, str] = {}
46def register_corpus(name: str, *, aliases: tuple[str, ...] = ()) -> Callable[[CorpusFactory], CorpusFactory]:
47 """Register a corpus factory and any compatibility aliases.
49 Args:
50 name (str): Canonical registry name.
51 aliases (tuple[str, ...]): Additional names resolving to the same factory.
53 Returns:
54 Callable[[CorpusFactory], CorpusFactory]: Factory decorator.
56 Raises:
57 ValueError: If a name is blank, repeated, or already registered.
58 """
59 requested_names = (name, *aliases)
60 if any(not requested_name.strip() for requested_name in requested_names):
61 raise ValueError("Corpus registry names must not be empty")
63 def decorator(factory: CorpusFactory) -> CorpusFactory:
64 if len(set(requested_names)) != len(requested_names):
65 raise ValueError(f"Corpus registration repeats a name in {requested_names!r}")
66 conflicts = [
67 requested_name
68 for requested_name in requested_names
69 if requested_name in _CORPUS_FACTORIES or requested_name in _CORPUS_ALIASES
70 ]
71 if conflicts:
72 raise ValueError(f"Corpus name {conflicts[0]!r} is already registered")
74 _CORPUS_FACTORIES[name] = factory
75 for alias in aliases:
76 _CORPUS_ALIASES[alias] = name
77 return factory
79 return decorator
82def corpus_factory(name: str) -> CorpusFactory:
83 """Return the factory registered under ``name`` or one of its aliases.
85 Args:
86 name (str): Canonical name or alias.
88 Returns:
89 CorpusFactory: Registered corpus constructor.
91 Raises:
92 KeyError: If ``name`` is not registered.
93 """
94 canonical_name = _CORPUS_ALIASES.get(name, name)
95 try:
96 return _CORPUS_FACTORIES[canonical_name]
97 except KeyError as error:
98 available = ", ".join(available_corpora()) or "<none>"
99 raise KeyError(f"Unknown corpus {name!r}. Available corpora: {available}") from error
102def build_corpus(specification: CorpusSpec) -> Corpus:
103 """Build the corpus described by ``specification``.
105 Args:
106 specification (CorpusSpec): Registered name and factory parameters.
108 Returns:
109 Corpus: Constructed corpus implementation.
111 Raises:
112 KeyError: If the requested corpus kind is not registered.
113 """
114 return corpus_factory(specification.kind)(specification)
117def corpus_spec_from_options(options: object) -> CorpusSpec:
118 """Build a specification from command options.
120 Args:
121 options (object): Configuration-like object carrying corpus attributes.
123 Returns:
124 CorpusSpec: Normalised construction specification.
126 Raises:
127 CorpusOptionsError: If an option cannot form a valid specification.
128 """
129 try:
130 return CorpusSpec.from_options(options)
131 except (TypeError, ValueError) as error:
132 raise CorpusOptionsError(str(error)) from error
135def build_corpus_from_options(options: object) -> Corpus:
136 """Build a configured corpus with one user-facing error type.
138 Args:
139 options (object): Configuration-like object carrying corpus attributes.
141 Returns:
142 Corpus: Constructed corpus implementation.
144 Raises:
145 CorpusOptionsError: If configuration, lookup, or external input cannot be used.
146 """
147 try:
148 return build_corpus(corpus_spec_from_options(options))
149 except (KeyError, TypeError, ValueError, OSError) as error:
150 if isinstance(error, CorpusOptionsError):
151 raise
152 message = error.args[0] if isinstance(error, KeyError) and error.args else str(error)
153 raise CorpusOptionsError(str(message)) from error
156def available_corpora() -> tuple[str, ...]:
157 """Return registered corpus names in sorted order."""
158 return tuple(sorted(_CORPUS_FACTORIES))