Coverage for src/wonka/dispatchers.py: 100%
42 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"""Dispatchers: factory classes that call other constructors.
3Contents:
4 Delegate (`base.Factory`): builds classes and/or instances using methods
5 that follow a naming convention and the `str` names of the types of the
6 first argument passed to the `create` class method.
7 Sourcerer (`base.Factory`, `abc.ABC`): builds classes and/or instances
8 using methods that follow a naming convention (set at
9 `options._METHOD_NAMER`) and a `dict` of types stored in the `sources`
10 class attribute.
12"""
14from __future__ import annotations
16import abc
17import dataclasses
18import inspect
19from typing import TYPE_CHECKING, Any, ClassVar
21from . import base, options, shared
23if TYPE_CHECKING:
24 from collections.abc import Callable, MutableMapping
27@dataclasses.dataclass
28class Delegate(base.Factory):
29 """Builds based on the `str` name of the type passed.
31 This factory acts as a dispatcher to call creation methods based on the type
32 or name of the type passed in a manner similar to `Sourcerer`. However,
33 unlike `Sourcerer`, `Delegate` only finds a matching creation method if the
34 `str` name of the type of `item` matches a substring of the creation method
35 name using the format of `options._METHOD_NAMER`. A `str` item is not named
36 by its type: the `str` itself is used as the name (so `'ini'` calls the
37 `from_ini` method with `'ini'`).
39 """
41 """ Class Methods """
43 @classmethod
44 def create(
45 cls,
46 item: Any,
47 parameters: base.Parameters | None = None,
48 **kwargs: base.Kwargs) -> Any:
49 """Creates an item based on `item` and possibly `parameters`.
51 Args:
52 item: data for construction of the returned item.
53 parameters: keyword arguments to pass or add to a created instance.
54 Defaults to `None`.
55 **kwargs: keyword arguments passed to the creation method.
57 Raises:
58 AttributeError: if an appropriate method does not exist for the
59 data type of `item`.
61 Returns:
62 Created item.
64 """
65 builder = _get_creation_method_name(item)
66 item = _get_from_builder_method(
67 factory = cls,
68 method = builder,
69 source = item,
70 **kwargs)
71 return shared.finalize(item = item, parameters = parameters)
74@dataclasses.dataclass
75class Sourcerer(base.Factory, abc.ABC):
76 """Builds based on compatibility with keys in the `sources` class attribute.
78 This factory acts as a dispatcher to call other methods based on the type
79 passed. Unlike `Delegate`, `Sourcerer` is more forgiving by allowing the
80 type passed to be a subtype or instance of the type listed as a key in the
81 `sources` class attribute. The keys of `sources` are checked in order, so
82 more specific types should be listed before more general ones.
84 The name for a `Sourcerer` is spelled the way it is instead of "Sorcerer"
85 because the `sources` attribute is used. This is inspired by the "Divinity:
86 Original Sin" games where the magic users are called "Sourcerers" because
87 they may manipulate the magical energy known as "source".
88 https://divinity.fandom.com/wiki/Sourcerer
90 Attributes:
91 sources: `dict` with keys that are types and values are substrings of
92 the names of methods to call when the key type is passed to the
93 `create` method. Defaults to an empty `dict`.
95 """
97 sources: ClassVar[MutableMapping[type[Any], str]] = {}
99 """ Class Methods """
101 @classmethod
102 def create(
103 cls,
104 item: Any,
105 parameters: base.Parameters | None = None,
106 **kwargs: base.Kwargs) -> Any:
107 """Creates an item based on `item` and possibly `parameters`.
109 Args:
110 item: data for construction of the returned item.
111 parameters: keyword arguments to pass or add to a created instance.
112 Defaults to `None`.
113 **kwargs: keyword arguments passed to the creation method.
115 Raises:
116 AttributeError: if the value matching the key `item` does not
117 correspond to a method in the `Sourcerer` subclass.
118 KeyError: if there is no key in `sources` matching the type for
119 `item`.
121 Returns:
122 Created item.
124 """
125 for kind, substring in cls.sources.items():
126 if _is_kind(item, kind):
127 builder = _get_creation_method_name(substring)
128 item = _get_from_builder_method(
129 factory = cls,
130 method = builder,
131 source = item,
132 **kwargs)
133 return shared.finalize(item = item, parameters = parameters)
134 message = f'{item} does not match any recognized types'
135 raise KeyError(message)
138""" Private Functions """
141def _get_creation_method_name(
142 source: Any,
143 method_namer: Callable[[Any], str] | None = None) -> str:
144 """Returns the creation method name for factories that call other methods.
146 Args:
147 source: source data for creating a method name.
148 method_namer: callable to create the creation method name. Defaults to
149 `None`. If it is `None`, the global namer stored in
150 `options._METHOD_NAMER` will be used.
152 Returns:
153 Name of the creation method to use.
155 """
156 if not isinstance(source, str):
157 source = options._KEY_NAMER(source)
158 namer = method_namer or options._METHOD_NAMER
159 return namer(source)
162def _get_from_builder_method(
163 factory: Any,
164 method: str,
165 source: Any,
166 **kwargs: base.Kwargs) -> Any:
167 """Returns constructed item from a builder method of `factory`.
169 Args:
170 factory: factory class or instance.
171 method: name of the method to use to construct an item.
172 source: the `source` data used to create item.
173 **kwargs: keyword arguments passed to the builder method.
175 Raises:
176 AttributeError: if `factory` has no method named `method`.
178 Returns:
179 Constructed item.
181 """
182 try:
183 builder = getattr(factory, method)
184 except AttributeError as error:
185 message = f'{method} does not exist in {factory}'
186 raise AttributeError(message) from error
187 return builder(source, **kwargs)
190def _is_kind(item: Any, kind: type[Any]) -> bool:
191 """Returns if `item` is an instance or subclass of `kind`.
193 Args:
194 item: item to evaluate.
195 kind: type to compare `item` to.
197 Returns:
198 Whether `item` is an instance or subclass of `kind`.
200 """
201 return (
202 isinstance(item, kind)
203 or (inspect.isclass(item) and issubclass(item, kind)))