Coverage for src/wonka/registries.py: 100%
46 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
1"""Factory classes that utilize explicit or implicit registries.
3Contents:
4 Registrar (`base.Factory`): builds classes and/or instances from a registry
5 stored in the `registry` class attribute.
6 AutoRegistrar (`Registrar`, `abc.ABC`): `Registrar` that automatically
7 registers its subclasses.
8 Subclasser (`base.Factory`, `abc.ABC`): builds classes and/or instances
9 from the `__subclasses__` method and a dynamically created registry
10 based upon it.
12"""
14from __future__ import annotations
16import abc
17import copy
18import dataclasses
19from typing import TYPE_CHECKING, Any, ClassVar
21from . import base, options, shared
23if TYPE_CHECKING:
24 from collections.abc import Hashable, Mapping
27@dataclasses.dataclass
28class Registrar(base.Factory):
29 """Builds an item from a registry.
31 Attributes:
32 registry: stores classes and/or instances to be used in item
33 construction. Defaults to an empty `dict`.
35 """
37 registry: ClassVar[base.GenericDict] = {}
39 """ Class Methods """
41 @classmethod
42 def create(
43 cls,
44 item: Hashable,
45 parameters: base.Parameters | None = None,
46 **kwargs: base.Kwargs) -> Any:
47 """Creates an item based on `item` and possibly `parameters`.
49 Args:
50 item: name corresponding to a key in `registry`.
51 parameters: keyword arguments to pass or add to a created instance.
52 Defaults to `None`.
53 **kwargs: allows subclass to take kwargs.
55 Raises:
56 KeyError: if a corresponding item in `registry` does not exist for
57 `item`.
59 Returns:
60 Created item.
62 """
63 item = _get_from_registry(item = item, registry = cls.registry)
64 return shared.finalize(item = item, parameters = parameters)
67@dataclasses.dataclass
68class AutoRegistrar(Registrar, abc.ABC):
69 """`Registrar` that automatically registers its subclasses.
71 Attributes:
72 registry: stores classes and/or instances to be used in item
73 construction. Defaults to an empty `dict`.
75 """
77 registry: ClassVar[base.GenericDict] = {}
79 """ Initialization Methods """
81 @classmethod
82 def __init_subclass__(cls, **kwargs: Any) -> None:
83 """Automatically registers subclasses.
85 Each direct subclass of `AutoRegistrar` that does not define its own
86 `registry` gets a new one so that unrelated class families do not share
87 (and pollute) a single registry. Deeper subclasses register in the
88 registry they inherit.
90 Args:
91 **kwargs: keyword arguments passed to the parent class
92 `__init_subclass__` method.
94 """
95 super().__init_subclass__(**kwargs)
96 if cls.registry is AutoRegistrar.registry:
97 cls.registry = {}
98 cls.registry[options._KEY_NAMER(cls)] = cls
101@dataclasses.dataclass
102class Subclasser(base.Factory, abc.ABC):
103 """Builds a subclass without requiring a storage attribute.
105 Unlike some other factories, this one does not require any class attributes.
106 Instead, it relies on pre-existing data and lazily adds keys to create
107 a registry facade.
109 This factory uses the subclasses stored in `__subclasses__` class method
110 that is automatically created with every class. It creates a `dict` on the
111 fly with key names based on `options._KEY_NAMER`. Because of this,
112 `Subclasser` should ordinarily be used as a mixin (although it could simply
113 be subclassed, if you prefer).
115 """
117 """ Class Methods """
119 @classmethod
120 def create(
121 cls,
122 item: Hashable,
123 parameters: base.Parameters | None = None,
124 **kwargs: base.Kwargs) -> Any:
125 """Creates an item based on `item` and possibly `parameters`.
127 A subclass in the `__subclasses__` class method is selected based on the
128 naming convention in `options._KEY_NAMER`.
130 Args:
131 item: name of the subclass to create.
132 parameters: keyword arguments to pass or add to a created instance.
133 Defaults to `None`.
134 **kwargs: allows subclass to take kwargs.
136 Raises:
137 KeyError: if a corresponding subclass does not exist for `item`.
139 Returns:
140 Created item.
142 """
143 keyer = options._KEY_NAMER
144 registry = {keyer(s): s for s in _get_all_subclasses(cls)}
145 item = _get_from_registry(item = item, registry = registry)
146 return shared.finalize(item = item, parameters = parameters)
149""" Private Functions """
152def _get_all_subclasses(item: type[Any]) -> list[type[Any]]:
153 """Returns a list of all subclasses of `item`, including indirect ones.
155 Each subclass appears once, in the order in which it is first found by a
156 depth-first search of `__subclasses__`.
158 Args:
159 item: class for which to find subclasses.
161 Returns:
162 List of all subclasses of `item`.
164 """
165 subclasses: dict[type[Any], None] = {}
166 for subclass in item.__subclasses__():
167 subclasses[subclass] = None
168 subclasses.update(dict.fromkeys(_get_all_subclasses(subclass)))
169 return list(subclasses)
172def _get_from_registry(item: Hashable, registry: Mapping[Any, Any]) -> Any:
173 """Returns a copy of a stored item in `registry` with the key of `item`.
175 Args:
176 item: key for item sought in `registry`.
177 registry: registry where the sought item is stored.
179 Raises:
180 KeyError: if `item` does not match any key in `registry`.
182 Returns:
183 A deep copy of an item stored in `registry`.
185 """
186 try:
187 return copy.deepcopy(registry[item])
188 except KeyError as error:
189 message = f'{item} was not found in the registry'
190 raise KeyError(message) from error