flextype 0.1.2__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {flextype-0.1.2 → flextype-0.2.0}/PKG-INFO +34 -4
- {flextype-0.1.2 → flextype-0.2.0}/README.md +32 -3
- {flextype-0.1.2 → flextype-0.2.0}/pyproject.toml +4 -3
- flextype-0.2.0/src/flextype/cast.py +229 -0
- flextype-0.2.0/src/flextype/isinstance.py +156 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype/registry_meta.py +50 -63
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype/singledispatch.py +106 -76
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype.egg-info/PKG-INFO +34 -4
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype.egg-info/SOURCES.txt +1 -0
- flextype-0.1.2/src/flextype/isinstance.py +0 -90
- {flextype-0.1.2 → flextype-0.2.0}/LICENSE +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/setup.cfg +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype/__init__.py +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype/load.py +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype/registry_pickle.py +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype.egg-info/dependency_links.txt +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype.egg-info/requires.txt +0 -0
- {flextype-0.1.2 → flextype-0.2.0}/src/flextype.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flextype
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Making types flexible.
|
|
5
5
|
Author-email: Clemens Damke <clemens@cortys.de>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3
|
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
19
|
Requires-Python: >=3.12.0
|
|
19
20
|
Description-Content-Type: text/markdown
|
|
20
21
|
License-File: LICENSE
|
|
@@ -48,9 +49,22 @@ uv add flextype
|
|
|
48
49
|
|
|
49
50
|
`lazy_isinstance` and `lazy_issubclass` work like `isinstance` and
|
|
50
51
|
`issubclass`, but type references may be real classes, fully qualified string
|
|
51
|
-
names, unions, or tuples. String references are
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
names, unions, or tuples. String references are resolved through `sys.modules`
|
|
53
|
+
and normal attribute lookup, supporting aliases, nested classes and dynamic
|
|
54
|
+
attributes. The resolver does not import missing modules. Unloaded module
|
|
55
|
+
references do not match.
|
|
56
|
+
Resolved references use regular `isinstance` / `issubclass` semantics, including
|
|
57
|
+
virtual subclasses and custom checking hooks, which may also have side effects.
|
|
58
|
+
|
|
59
|
+
Use `"pkg.submodule:Outer.Type"` to specify the module boundary explicitly.
|
|
60
|
+
Resolution waits only for that module; once it is loaded, missing attributes
|
|
61
|
+
raise `AttributeError`. Dotted references such as `"pkg.submodule.Type"` use the
|
|
62
|
+
longest loaded module prefix, even when a shorter module exposes a different
|
|
63
|
+
nested attribute. If lookup fails, they wait only when a longer module prefix
|
|
64
|
+
could still load. Thus `"pkg.C"` raises if `pkg` is loaded but lacks `C`.
|
|
65
|
+
|
|
66
|
+
Lazy and delayed dispatcher registrations follow the same rules. Once a
|
|
67
|
+
reference resolves to a class, later imports do not retarget that registration.
|
|
54
68
|
|
|
55
69
|
```python
|
|
56
70
|
from pathlib import Path
|
|
@@ -206,6 +220,22 @@ registration concept to instance-level registrations. `Registry` and
|
|
|
206
220
|
`RegistryMeta` expose the same mechanism for non-protocol marker classes, and
|
|
207
221
|
the metaclasses are exported too when direct metaclass use is the better fit.
|
|
208
222
|
|
|
223
|
+
Class registries accept the same dotted and `module:qualname` references as
|
|
224
|
+
`flexdispatch`. Available classes are registered immediately; unresolved module
|
|
225
|
+
references are retried on registration, instance checks without a positive
|
|
226
|
+
instance-cache hit, and uncached subclass checks. Resolution registers all
|
|
227
|
+
available references, not just a name matching
|
|
228
|
+
the class being checked. Protocol registries support pending references only
|
|
229
|
+
with `structural_checking=False`; already-loaded string references are eager
|
|
230
|
+
registrations.
|
|
231
|
+
|
|
232
|
+
Subclass checks use the normal ABC cache and hook. Consequently, an alias to a
|
|
233
|
+
class that previously failed a subclass check can remain a cached miss after
|
|
234
|
+
its module loads, until another uncached check or registration triggers
|
|
235
|
+
promotion. Prefer canonical class paths for registrations; aliases are only
|
|
236
|
+
weakly supported. Ordinary `lazy_isinstance` / `lazy_issubclass` lookups remain
|
|
237
|
+
uncached and may use aliases directly.
|
|
238
|
+
|
|
209
239
|
## Development
|
|
210
240
|
|
|
211
241
|
```sh
|
|
@@ -25,9 +25,22 @@ uv add flextype
|
|
|
25
25
|
|
|
26
26
|
`lazy_isinstance` and `lazy_issubclass` work like `isinstance` and
|
|
27
27
|
`issubclass`, but type references may be real classes, fully qualified string
|
|
28
|
-
names, unions, or tuples. String references are
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
names, unions, or tuples. String references are resolved through `sys.modules`
|
|
29
|
+
and normal attribute lookup, supporting aliases, nested classes and dynamic
|
|
30
|
+
attributes. The resolver does not import missing modules. Unloaded module
|
|
31
|
+
references do not match.
|
|
32
|
+
Resolved references use regular `isinstance` / `issubclass` semantics, including
|
|
33
|
+
virtual subclasses and custom checking hooks, which may also have side effects.
|
|
34
|
+
|
|
35
|
+
Use `"pkg.submodule:Outer.Type"` to specify the module boundary explicitly.
|
|
36
|
+
Resolution waits only for that module; once it is loaded, missing attributes
|
|
37
|
+
raise `AttributeError`. Dotted references such as `"pkg.submodule.Type"` use the
|
|
38
|
+
longest loaded module prefix, even when a shorter module exposes a different
|
|
39
|
+
nested attribute. If lookup fails, they wait only when a longer module prefix
|
|
40
|
+
could still load. Thus `"pkg.C"` raises if `pkg` is loaded but lacks `C`.
|
|
41
|
+
|
|
42
|
+
Lazy and delayed dispatcher registrations follow the same rules. Once a
|
|
43
|
+
reference resolves to a class, later imports do not retarget that registration.
|
|
31
44
|
|
|
32
45
|
```python
|
|
33
46
|
from pathlib import Path
|
|
@@ -183,6 +196,22 @@ registration concept to instance-level registrations. `Registry` and
|
|
|
183
196
|
`RegistryMeta` expose the same mechanism for non-protocol marker classes, and
|
|
184
197
|
the metaclasses are exported too when direct metaclass use is the better fit.
|
|
185
198
|
|
|
199
|
+
Class registries accept the same dotted and `module:qualname` references as
|
|
200
|
+
`flexdispatch`. Available classes are registered immediately; unresolved module
|
|
201
|
+
references are retried on registration, instance checks without a positive
|
|
202
|
+
instance-cache hit, and uncached subclass checks. Resolution registers all
|
|
203
|
+
available references, not just a name matching
|
|
204
|
+
the class being checked. Protocol registries support pending references only
|
|
205
|
+
with `structural_checking=False`; already-loaded string references are eager
|
|
206
|
+
registrations.
|
|
207
|
+
|
|
208
|
+
Subclass checks use the normal ABC cache and hook. Consequently, an alias to a
|
|
209
|
+
class that previously failed a subclass check can remain a cached miss after
|
|
210
|
+
its module loads, until another uncached check or registration triggers
|
|
211
|
+
promotion. Prefer canonical class paths for registrations; aliases are only
|
|
212
|
+
weakly supported. Ordinary `lazy_isinstance` / `lazy_issubclass` lookups remain
|
|
213
|
+
uncached and may use aliases directly.
|
|
214
|
+
|
|
186
215
|
## Development
|
|
187
216
|
|
|
188
217
|
```sh
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "flextype"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Making types flexible."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -25,6 +25,7 @@ classifiers = [
|
|
|
25
25
|
"Programming Language :: Python :: 3.12",
|
|
26
26
|
"Programming Language :: Python :: 3.13",
|
|
27
27
|
"Programming Language :: Python :: 3.14",
|
|
28
|
+
"Programming Language :: Python :: 3.15",
|
|
28
29
|
]
|
|
29
30
|
|
|
30
31
|
[project.urls]
|
|
@@ -37,8 +38,8 @@ include = ["flextype", "flextype.*"]
|
|
|
37
38
|
|
|
38
39
|
[dependency-groups]
|
|
39
40
|
lint = [
|
|
40
|
-
"ruff>=0.
|
|
41
|
-
"ty>=0.0.
|
|
41
|
+
"ruff>=0.17.1",
|
|
42
|
+
"ty>=0.0.89",
|
|
42
43
|
]
|
|
43
44
|
test = [
|
|
44
45
|
"pytest>=8.0",
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Types with self-declared casting capabilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from contextvars import ContextVar
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from heapq import heappop, heappush
|
|
9
|
+
from itertools import chain, count
|
|
10
|
+
import sys
|
|
11
|
+
from typing import TYPE_CHECKING, Any, overload
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Callable, Generator
|
|
15
|
+
|
|
16
|
+
if sys.version_info >= (3, 13):
|
|
17
|
+
from typing import TypeIs
|
|
18
|
+
else:
|
|
19
|
+
from typing_extensions import TypeIs
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(slots=True, weakref_slot=True, frozen=True, repr=True)
|
|
23
|
+
class Caster[S, T](ABC):
|
|
24
|
+
"""A type that can be cast to another type."""
|
|
25
|
+
|
|
26
|
+
source: type[S]
|
|
27
|
+
"""The source type from which this cast can be cast."""
|
|
28
|
+
target: type[T]
|
|
29
|
+
"""The target type to which this cast can be cast."""
|
|
30
|
+
cost: int = field(default=1, kw_only=True)
|
|
31
|
+
"""The cost of the cast. Lower costs are preferred."""
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def __call__(self, value: S) -> T:
|
|
35
|
+
"""Cast the value to the target type."""
|
|
36
|
+
|
|
37
|
+
def valid(self, value: object) -> TypeIs[S]:
|
|
38
|
+
"""Validate that the value can be cast to the target type."""
|
|
39
|
+
return isinstance(value, self.source)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(slots=True, weakref_slot=True, frozen=True, repr=True)
|
|
43
|
+
class ConcreteCaster[S, T](Caster[S, T]):
|
|
44
|
+
"""A type that can be cast to another type."""
|
|
45
|
+
|
|
46
|
+
cast_fn: Callable[[S], T]
|
|
47
|
+
"""The function that performs the cast."""
|
|
48
|
+
|
|
49
|
+
def __call__(self, value: S) -> T:
|
|
50
|
+
"""Cast the value to the target type."""
|
|
51
|
+
return self.cast_fn(value)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(slots=True, weakref_slot=True, frozen=True, repr=True)
|
|
55
|
+
class _IdentityCaster[S, T](Caster[S, T]):
|
|
56
|
+
"""A zero-cost upcast that leaves the value unchanged."""
|
|
57
|
+
|
|
58
|
+
cost: int = field(default=0, init=False)
|
|
59
|
+
|
|
60
|
+
def __call__(self, value: S) -> T:
|
|
61
|
+
"""Return the value unchanged."""
|
|
62
|
+
return value # ty: ignore[invalid-return-type]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _flatten_cast_chain(cast_chain: tuple[Caster[Any, Any], ...]) -> Generator[Caster[Any, Any], None, None]:
|
|
66
|
+
"""Flatten a chain of casts into a tuple of casts."""
|
|
67
|
+
for cast in cast_chain:
|
|
68
|
+
if isinstance(cast, _IdentityCaster):
|
|
69
|
+
continue
|
|
70
|
+
if isinstance(cast, _IndirectCaster):
|
|
71
|
+
yield from _flatten_cast_chain(cast.cast_chain)
|
|
72
|
+
else:
|
|
73
|
+
yield cast
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(slots=True, weakref_slot=True, frozen=True, repr=True)
|
|
77
|
+
class _IndirectCaster[S, T](Caster[S, T]):
|
|
78
|
+
"""A type that can be cast to another type via an intermediate type."""
|
|
79
|
+
|
|
80
|
+
cast_chain: tuple[Caster[Any, Any], ...]
|
|
81
|
+
"""The chain of casts that perform the cast."""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self, source: type[S], target: type[T], cast_chain: tuple[Caster[Any, Any], ...], *, flatten: bool = True
|
|
85
|
+
) -> None:
|
|
86
|
+
"""Initialize the indirect cast."""
|
|
87
|
+
Caster.__init__(self, source=source, target=target, cost=sum(cast.cost for cast in cast_chain))
|
|
88
|
+
if flatten:
|
|
89
|
+
cast_chain = tuple(_flatten_cast_chain(cast_chain))
|
|
90
|
+
object.__setattr__(self, "cast_chain", cast_chain)
|
|
91
|
+
|
|
92
|
+
def __call__(self, value: S) -> T:
|
|
93
|
+
"""Cast the value to the target type via the intermediate type."""
|
|
94
|
+
for cast in self.cast_chain:
|
|
95
|
+
value = cast(value)
|
|
96
|
+
return value # ty: ignore[invalid-return-type]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(slots=True, weakref_slot=True)
|
|
100
|
+
class CasterGraph:
|
|
101
|
+
"""A graph of casters between types."""
|
|
102
|
+
|
|
103
|
+
casts: dict[type, dict[type, ConcreteCaster]] = field(default_factory=dict)
|
|
104
|
+
"""The graph of casts between types."""
|
|
105
|
+
indirect_casts: dict[type, dict[type, Caster | None]] = field(default_factory=dict)
|
|
106
|
+
"""Cached minimum-cost casts, including unreachable pairs."""
|
|
107
|
+
|
|
108
|
+
def add_caster(self, cast: ConcreteCaster) -> None:
|
|
109
|
+
"""Add a cast to the graph."""
|
|
110
|
+
self.indirect_casts.clear()
|
|
111
|
+
self.casts.setdefault(cast.source, {})[cast.target] = cast
|
|
112
|
+
|
|
113
|
+
def get_direct_caster[S, T](self, source: type[S], target: type[T]) -> ConcreteCaster[S, T] | None:
|
|
114
|
+
"""Get a cast from the graph."""
|
|
115
|
+
if source not in self.casts:
|
|
116
|
+
return None
|
|
117
|
+
return self.casts[source].get(target)
|
|
118
|
+
|
|
119
|
+
def get_cached_caster[S, T](self, source: type[S], target: type[T]) -> Caster[S, T] | None:
|
|
120
|
+
"""Get a (cached) indirect cast from the graph."""
|
|
121
|
+
if issubclass(source, target):
|
|
122
|
+
return _IdentityCaster(source, target)
|
|
123
|
+
if source not in self.indirect_casts:
|
|
124
|
+
return None
|
|
125
|
+
return self.indirect_casts[source].get(target)
|
|
126
|
+
|
|
127
|
+
def get_caster[S, T](self, source: type[S], target: type[T]) -> Caster[S, T]:
|
|
128
|
+
"""Find a minimum-cost cast, allowing zero-cost upcasts throughout the path."""
|
|
129
|
+
if (cached_cast := self.get_cached_caster(source, target)) is not None:
|
|
130
|
+
return cached_cast
|
|
131
|
+
|
|
132
|
+
# Search for best indirect cast via Dijkstra and cache it for future use:
|
|
133
|
+
visited: set[type] = set()
|
|
134
|
+
costs: dict[type, int] = {source: 0}
|
|
135
|
+
predecessors: dict[type, Caster] = {}
|
|
136
|
+
# A counter prevents heap ties from comparing type objects.
|
|
137
|
+
order = count()
|
|
138
|
+
queue: list[tuple[int, int, type]] = [(0, next(order), source)]
|
|
139
|
+
result: Caster[S, T] | None = None
|
|
140
|
+
|
|
141
|
+
while queue:
|
|
142
|
+
cost, _, current = heappop(queue)
|
|
143
|
+
if current in visited:
|
|
144
|
+
continue
|
|
145
|
+
visited.add(current)
|
|
146
|
+
if issubclass(current, target):
|
|
147
|
+
cast_chain: list[ConcreteCaster] = []
|
|
148
|
+
while current is not source:
|
|
149
|
+
edge = predecessors[current]
|
|
150
|
+
if isinstance(edge, ConcreteCaster):
|
|
151
|
+
cast_chain.append(edge)
|
|
152
|
+
current = edge.source
|
|
153
|
+
cast_chain.reverse()
|
|
154
|
+
if len(cast_chain) == 1:
|
|
155
|
+
direct = cast_chain[0]
|
|
156
|
+
result = (
|
|
157
|
+
direct
|
|
158
|
+
if direct.source is source and direct.target is target
|
|
159
|
+
else ConcreteCaster(source, target, direct.cast_fn, cost=direct.cost)
|
|
160
|
+
)
|
|
161
|
+
else:
|
|
162
|
+
result = _IndirectCaster(source, target, tuple(cast_chain), flatten=False)
|
|
163
|
+
break
|
|
164
|
+
|
|
165
|
+
edges = chain(
|
|
166
|
+
self.casts.get(current, {}).values(),
|
|
167
|
+
(_IdentityCaster(current, base) for base in current.__bases__ if base not in visited),
|
|
168
|
+
)
|
|
169
|
+
for edge in edges:
|
|
170
|
+
if edge.target in visited:
|
|
171
|
+
continue
|
|
172
|
+
candidate = cost + edge.cost
|
|
173
|
+
if edge.target not in costs or candidate < costs[edge.target]:
|
|
174
|
+
costs[edge.target] = candidate
|
|
175
|
+
predecessors[edge.target] = edge
|
|
176
|
+
heappush(queue, (candidate, next(order), edge.target))
|
|
177
|
+
|
|
178
|
+
if result is None:
|
|
179
|
+
msg = f"No cast found from {source} to {target}."
|
|
180
|
+
raise TypeError(msg)
|
|
181
|
+
|
|
182
|
+
self.indirect_casts.setdefault(source, {})[target] = result
|
|
183
|
+
return result
|
|
184
|
+
|
|
185
|
+
def cast[S, T](self, value: S, target: type[T]) -> T:
|
|
186
|
+
"""Cast a value to the target type."""
|
|
187
|
+
source = type(value)
|
|
188
|
+
caster = self.get_caster(source, target)
|
|
189
|
+
return caster(value)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
CASTS = ContextVar("CASTS", default=CasterGraph()) # noqa: B039
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@overload
|
|
196
|
+
def caster[S, T](
|
|
197
|
+
source: type[S], target: type[T], cast_fn: None = None, *, cost: int = 1, graph: CasterGraph | None = None
|
|
198
|
+
) -> Callable[[Callable[[S], T]], ConcreteCaster[S, T]]: ...
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@overload
|
|
202
|
+
def caster[S, T](
|
|
203
|
+
source: type[S], target: type[T], cast_fn: Callable[[S], T], *, cost: int = 1, graph: CasterGraph | None = None
|
|
204
|
+
) -> ConcreteCaster[S, T]: ...
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def caster[S, T](
|
|
208
|
+
source: type[S],
|
|
209
|
+
target: type[T],
|
|
210
|
+
cast_fn: Callable[[S], T] | None = None,
|
|
211
|
+
*,
|
|
212
|
+
cost: int = 1,
|
|
213
|
+
graph: CasterGraph | None = None,
|
|
214
|
+
) -> ConcreteCaster[S, T] | Callable[[Callable[[S], T]], ConcreteCaster[S, T]]:
|
|
215
|
+
"""Register a caster directly, or return a decorator when no function is given."""
|
|
216
|
+
|
|
217
|
+
def decorate(cast_fn: Callable[[S], T]) -> ConcreteCaster[S, T]:
|
|
218
|
+
cast = ConcreteCaster(source, target, cast_fn, cost=cost)
|
|
219
|
+
active_graph = CASTS.get() if graph is None else graph
|
|
220
|
+
active_graph.add_caster(cast)
|
|
221
|
+
return cast
|
|
222
|
+
|
|
223
|
+
return decorate if cast_fn is None else decorate(cast_fn)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cast[S, T](value: S, target: type[T], *, graph: CasterGraph | None = None) -> T:
|
|
227
|
+
"""Cast a value to the target type."""
|
|
228
|
+
active_graph = CASTS.get() if graph is None else graph
|
|
229
|
+
return active_graph.cast(value, target)
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""A lazy version of isinstance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from types import ModuleType, UnionType
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Union, get_args, get_origin
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
type LazyType = type | str | UnionType | tuple[LazyType, ...]
|
|
13
|
+
|
|
14
|
+
_UNRESOLVED = object()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _split_type_name(name: str) -> tuple[str, str, bool]:
|
|
18
|
+
"""Split module and attributes, recording an explicit module boundary."""
|
|
19
|
+
if ":" in name:
|
|
20
|
+
module, _, attributes = name.partition(":")
|
|
21
|
+
if not module or not attributes or ":" in attributes:
|
|
22
|
+
msg = f"Invalid type reference: {name!r}"
|
|
23
|
+
raise ValueError(msg)
|
|
24
|
+
return module, attributes, True
|
|
25
|
+
module, _, attributes = name.rpartition(".")
|
|
26
|
+
return module or "builtins", attributes, False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _module_name_precheck(index: set[str]) -> Callable[[], bool]:
|
|
30
|
+
"""Check live module presence; rebuild this callable when the index changes."""
|
|
31
|
+
if len(index) == 1:
|
|
32
|
+
name = next(iter(index))
|
|
33
|
+
return lambda: sys.modules.get(name) is not None
|
|
34
|
+
return lambda: not sys.modules.keys().isdisjoint(index)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _resolve_loaded_type(name: str, pending_modules: set[str] | None = None) -> object:
|
|
38
|
+
"""Resolve the longest loaded module prefix, or an explicit module:qualname.
|
|
39
|
+
|
|
40
|
+
Missing attributes are errors unless a longer module prefix could still load.
|
|
41
|
+
Once a loaded module is selected, lookup never falls back to a shorter prefix.
|
|
42
|
+
If requested, record unloaded prefixes as they are examined. Callers should
|
|
43
|
+
retain these only if the reference remains pending.
|
|
44
|
+
"""
|
|
45
|
+
module_name, attributes, explicit = _split_type_name(name)
|
|
46
|
+
definitive = True
|
|
47
|
+
while module_name:
|
|
48
|
+
module = sys.modules.get(module_name)
|
|
49
|
+
if module is not None and isinstance(module, ModuleType):
|
|
50
|
+
obj = module
|
|
51
|
+
try:
|
|
52
|
+
for part in attributes.split("."):
|
|
53
|
+
obj = getattr(obj, part)
|
|
54
|
+
except AttributeError as exc:
|
|
55
|
+
if definitive:
|
|
56
|
+
exc.add_note(f"While resolving type reference {name!r}")
|
|
57
|
+
raise
|
|
58
|
+
return _UNRESOLVED
|
|
59
|
+
return obj
|
|
60
|
+
if pending_modules is not None:
|
|
61
|
+
pending_modules.add(module_name)
|
|
62
|
+
if explicit or "." not in module_name:
|
|
63
|
+
break
|
|
64
|
+
module_name, _, part = module_name.rpartition(".")
|
|
65
|
+
attributes = f"{part}.{attributes}"
|
|
66
|
+
definitive = False
|
|
67
|
+
return _UNRESOLVED
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _is_union_type(cls: Any) -> bool: # noqa: ANN401
|
|
71
|
+
return get_origin(cls) in {Union, UnionType}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _split_lazy_type(lazy_type: LazyType, pending_modules: set[str] | None = None) -> tuple[set[type], set[str]]:
|
|
75
|
+
"""Split classinfo into a set of types and a set of strings."""
|
|
76
|
+
if isinstance(lazy_type, str):
|
|
77
|
+
types: set[type] = set()
|
|
78
|
+
strings: set[str] = set()
|
|
79
|
+
for t in lazy_type.split("|"):
|
|
80
|
+
st = t.strip()
|
|
81
|
+
unloaded = set() if pending_modules is not None else None
|
|
82
|
+
resolved_t = _resolve_loaded_type(st, unloaded)
|
|
83
|
+
if resolved_t is not _UNRESOLVED and isinstance(resolved_t, type):
|
|
84
|
+
types.add(resolved_t)
|
|
85
|
+
else:
|
|
86
|
+
strings.add(st)
|
|
87
|
+
if pending_modules is not None and unloaded:
|
|
88
|
+
pending_modules.update(unloaded)
|
|
89
|
+
return types, strings
|
|
90
|
+
if isinstance(lazy_type, type):
|
|
91
|
+
return {lazy_type}, set()
|
|
92
|
+
if isinstance(lazy_type, tuple):
|
|
93
|
+
types: set[type] = set()
|
|
94
|
+
strings: set[str] = set()
|
|
95
|
+
for item in lazy_type:
|
|
96
|
+
t, s = _split_lazy_type(item, pending_modules)
|
|
97
|
+
types.update(t)
|
|
98
|
+
strings.update(s)
|
|
99
|
+
return types, strings
|
|
100
|
+
if _is_union_type(lazy_type):
|
|
101
|
+
types = set()
|
|
102
|
+
strings = set()
|
|
103
|
+
for arg in get_args(lazy_type):
|
|
104
|
+
t, s = _split_lazy_type(arg, pending_modules)
|
|
105
|
+
types.update(t)
|
|
106
|
+
strings.update(s)
|
|
107
|
+
return types, strings
|
|
108
|
+
|
|
109
|
+
msg = f"Invalid classinfo: {lazy_type!r}"
|
|
110
|
+
raise TypeError(msg)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def lazy_isinstance(obj: object, class_or_tuple: LazyType, /) -> bool:
|
|
114
|
+
"""Check instances, resolving string references from loaded modules.
|
|
115
|
+
|
|
116
|
+
Unloaded module references do not match; definitively missing attributes raise.
|
|
117
|
+
Resolved references use ordinary isinstance semantics. Attribute lookup and
|
|
118
|
+
checking hooks may have side effects.
|
|
119
|
+
"""
|
|
120
|
+
if isinstance(class_or_tuple, type):
|
|
121
|
+
return isinstance(obj, class_or_tuple)
|
|
122
|
+
if isinstance(class_or_tuple, str):
|
|
123
|
+
for name in class_or_tuple.split("|"):
|
|
124
|
+
resolved = _resolve_loaded_type(name.strip())
|
|
125
|
+
if resolved is not _UNRESOLVED and isinstance(obj, resolved): # ty:ignore[invalid-argument-type]
|
|
126
|
+
return True
|
|
127
|
+
return False
|
|
128
|
+
if isinstance(class_or_tuple, tuple):
|
|
129
|
+
for item in class_or_tuple: # noqa: SIM110 - Avoid generator allocation on the hot path.
|
|
130
|
+
if lazy_isinstance(obj, item):
|
|
131
|
+
return True
|
|
132
|
+
return False
|
|
133
|
+
return isinstance(obj, class_or_tuple)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def lazy_issubclass(cls: type, class_or_tuple: LazyType, /) -> bool:
|
|
137
|
+
"""Check subclasses, resolving string references from loaded modules.
|
|
138
|
+
|
|
139
|
+
Unloaded module references do not match; definitively missing attributes raise.
|
|
140
|
+
Resolved references use ordinary issubclass semantics. Attribute lookup and
|
|
141
|
+
checking hooks may have side effects.
|
|
142
|
+
"""
|
|
143
|
+
if isinstance(class_or_tuple, type):
|
|
144
|
+
return issubclass(cls, class_or_tuple)
|
|
145
|
+
if isinstance(class_or_tuple, str):
|
|
146
|
+
for name in class_or_tuple.split("|"):
|
|
147
|
+
resolved = _resolve_loaded_type(name.strip())
|
|
148
|
+
if resolved is not _UNRESOLVED and issubclass(cls, resolved): # ty:ignore[invalid-argument-type]
|
|
149
|
+
return True
|
|
150
|
+
return False
|
|
151
|
+
if isinstance(class_or_tuple, tuple):
|
|
152
|
+
for item in class_or_tuple: # noqa: SIM110 - Avoid generator allocation on the hot path.
|
|
153
|
+
if lazy_issubclass(cls, item):
|
|
154
|
+
return True
|
|
155
|
+
return False
|
|
156
|
+
return issubclass(cls, class_or_tuple)
|
|
@@ -5,10 +5,10 @@ from __future__ import annotations
|
|
|
5
5
|
from abc import ABCMeta
|
|
6
6
|
import functools
|
|
7
7
|
import sys
|
|
8
|
-
from typing import TYPE_CHECKING, Any, Protocol, cast, overload, runtime_checkable
|
|
8
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Protocol, cast, overload, runtime_checkable
|
|
9
9
|
from weakref import ReferenceType, WeakSet, ref
|
|
10
10
|
|
|
11
|
-
from flextype.isinstance import
|
|
11
|
+
from flextype.isinstance import _module_name_precheck, _split_lazy_type
|
|
12
12
|
|
|
13
13
|
if sys.version_info >= (3, 13):
|
|
14
14
|
from typing import is_protocol
|
|
@@ -26,6 +26,8 @@ EXCLUDED_ATTRS = frozenset(
|
|
|
26
26
|
"_instance_registry",
|
|
27
27
|
"_negative_instance_registry",
|
|
28
28
|
"_string_registry",
|
|
29
|
+
"_pending_modules",
|
|
30
|
+
"_pending_module_check",
|
|
29
31
|
"_structural_checking",
|
|
30
32
|
}
|
|
31
33
|
)
|
|
@@ -121,19 +123,18 @@ class _IdentityWeakSet[T: object]:
|
|
|
121
123
|
return False
|
|
122
124
|
|
|
123
125
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
def _make_lazy_subclass_hook(pre_hook: Callable | classmethod | None = None) -> classmethod:
|
|
127
|
+
"""Promote available references on uncached checks, then honor a custom hook."""
|
|
128
|
+
if isinstance(pre_hook, classmethod):
|
|
129
|
+
pre_hook = pre_hook.__func__
|
|
130
|
+
callback = cast("Callable[[RegistryMeta, type], bool] | None", pre_hook)
|
|
128
131
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
string_registry.remove(string_type)
|
|
134
|
-
cls._register(real_type)
|
|
132
|
+
def hook(cls: RegistryMeta, subclass: type, /) -> bool:
|
|
133
|
+
if cls._string_registry and cls._pending_module_check():
|
|
134
|
+
cls._resolve_pending_registrations()
|
|
135
|
+
return NotImplemented if callback is None else callback(cls, subclass)
|
|
135
136
|
|
|
136
|
-
return
|
|
137
|
+
return classmethod(hook)
|
|
137
138
|
|
|
138
139
|
|
|
139
140
|
@classmethod
|
|
@@ -142,23 +143,6 @@ def _nop_instancehook[T](_cls: RegistryMeta[T], _instance: object, /) -> bool:
|
|
|
142
143
|
return NotImplemented
|
|
143
144
|
|
|
144
145
|
|
|
145
|
-
def _lazy_subclass_hook_with_pre_hook[T](
|
|
146
|
-
pre_hook: Callable[[RegistryMeta[T], type], bool],
|
|
147
|
-
) -> Callable[[RegistryMeta[T], type], bool]:
|
|
148
|
-
"""A __subclasshook__ that checks the pre_hook before checking the string registry."""
|
|
149
|
-
|
|
150
|
-
@classmethod
|
|
151
|
-
def hook(cls: RegistryMeta[T], subclass: type, /) -> bool:
|
|
152
|
-
pre_res = pre_hook(cls, subclass)
|
|
153
|
-
|
|
154
|
-
if pre_res is not NotImplemented:
|
|
155
|
-
return pre_res
|
|
156
|
-
|
|
157
|
-
return _lazy_subclass_hook.__func__(cls, subclass)
|
|
158
|
-
|
|
159
|
-
return hook
|
|
160
|
-
|
|
161
|
-
|
|
162
146
|
class List(list):
|
|
163
147
|
"""A wrapper around list that allows weak references, to allow lists to be registered in registries."""
|
|
164
148
|
|
|
@@ -189,7 +173,9 @@ class RegistryMeta[T: object](ABCMeta):
|
|
|
189
173
|
_instance_registry: _IdentityWeakSet[T]
|
|
190
174
|
_negative_instance_registry: _IdentityWeakSet[object]
|
|
191
175
|
_string_registry: set[str]
|
|
192
|
-
|
|
176
|
+
_pending_modules: set[str]
|
|
177
|
+
_pending_module_check: Callable[[], bool]
|
|
178
|
+
known_registry_classes: ClassVar[WeakSet[type]] = WeakSet()
|
|
193
179
|
|
|
194
180
|
def __init__(
|
|
195
181
|
cls,
|
|
@@ -205,17 +191,11 @@ class RegistryMeta[T: object](ABCMeta):
|
|
|
205
191
|
cls._instance_registry: _IdentityWeakSet[T] = _IdentityWeakSet()
|
|
206
192
|
cls._negative_instance_registry: _IdentityWeakSet[object] = _IdentityWeakSet()
|
|
207
193
|
cls._string_registry: set[str] = set()
|
|
194
|
+
cls._pending_modules = set()
|
|
195
|
+
cls._pending_module_check = _module_name_precheck(cls._pending_modules)
|
|
208
196
|
|
|
209
197
|
if not is_protocol(cls):
|
|
210
|
-
|
|
211
|
-
if subclasshook is None:
|
|
212
|
-
subclasshook = _lazy_subclass_hook
|
|
213
|
-
else:
|
|
214
|
-
if isinstance(subclasshook, classmethod):
|
|
215
|
-
subclasshook = subclasshook.__func__
|
|
216
|
-
subclasshook = _lazy_subclass_hook_with_pre_hook(subclasshook)
|
|
217
|
-
|
|
218
|
-
cls.__subclasshook__ = subclasshook # ty: ignore[invalid-assignment]
|
|
198
|
+
cls.__subclasshook__ = _make_lazy_subclass_hook(namespace.get("__subclasshook__")) # ty: ignore[invalid-assignment]
|
|
219
199
|
|
|
220
200
|
RegistryMeta.known_registry_classes.add(cls)
|
|
221
201
|
|
|
@@ -243,17 +223,37 @@ class RegistryMeta[T: object](ABCMeta):
|
|
|
243
223
|
|
|
244
224
|
def register(cls, subclass: LazyType) -> type:
|
|
245
225
|
"""Register a (lazy) subclass or a set of subclasses in registry."""
|
|
246
|
-
|
|
226
|
+
if cls._string_registry and cls._pending_module_check():
|
|
227
|
+
cls._resolve_pending_registrations()
|
|
228
|
+
pending_modules: set[str] = set()
|
|
229
|
+
types, strings = _split_lazy_type(subclass, pending_modules)
|
|
247
230
|
for t in types:
|
|
248
231
|
cls._register(t)
|
|
249
232
|
|
|
250
233
|
cls._register_lazy(strings)
|
|
234
|
+
if strings:
|
|
235
|
+
cls._pending_modules.update(pending_modules)
|
|
236
|
+
cls._pending_module_check = _module_name_precheck(cls._pending_modules)
|
|
251
237
|
cls._negative_instance_registry = _IdentityWeakSet()
|
|
252
238
|
|
|
253
239
|
if isinstance(subclass, type):
|
|
254
240
|
return subclass
|
|
255
241
|
return cls
|
|
256
242
|
|
|
243
|
+
def _resolve_pending_registrations(cls) -> None:
|
|
244
|
+
"""Promote available references independently of the class being checked."""
|
|
245
|
+
pending_modules: set[str] = set()
|
|
246
|
+
types, strings = _split_lazy_type(tuple(cls._string_registry), pending_modules)
|
|
247
|
+
# Publish the remaining queue before ABCMeta.register re-enters subclass
|
|
248
|
+
# checking. No registration-in-progress flag or recursive scan is needed.
|
|
249
|
+
cls._string_registry = strings
|
|
250
|
+
cls._pending_modules = pending_modules
|
|
251
|
+
cls._pending_module_check = _module_name_precheck(pending_modules)
|
|
252
|
+
for subclass in types:
|
|
253
|
+
cls._register(subclass)
|
|
254
|
+
if types:
|
|
255
|
+
cls._negative_instance_registry = _IdentityWeakSet()
|
|
256
|
+
|
|
257
257
|
def _register_instance[Q](cls: RegistryMeta[T], instance: Q) -> Q:
|
|
258
258
|
try:
|
|
259
259
|
cls._instance_registry.add(instance) # ty:ignore[invalid-argument-type]
|
|
@@ -328,13 +328,12 @@ class RegistryMeta[T: object](ABCMeta):
|
|
|
328
328
|
|
|
329
329
|
def __instancecheck__(cls, instance: object) -> bool:
|
|
330
330
|
"""Check if an instance is in the registry."""
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
pass
|
|
331
|
+
if instance in cls._instance_registry:
|
|
332
|
+
return True
|
|
333
|
+
if cls._string_registry and cls._pending_module_check():
|
|
334
|
+
cls._resolve_pending_registrations()
|
|
335
|
+
if instance in cls._negative_instance_registry:
|
|
336
|
+
return False
|
|
338
337
|
|
|
339
338
|
instancehook = getattr(cls, "__instancehook__", None)
|
|
340
339
|
if instancehook is not None:
|
|
@@ -414,26 +413,14 @@ class ProtocolRegistryMeta[T](RegistryMeta[T], type(Protocol)):
|
|
|
414
413
|
del protocol_attrs
|
|
415
414
|
|
|
416
415
|
if not structural_checking:
|
|
417
|
-
# Override Protocol's
|
|
418
|
-
#
|
|
416
|
+
# Override Protocol's structural hook, preserving an explicitly
|
|
417
|
+
# declared custom hook and resolving available lazy references.
|
|
419
418
|
|
|
420
419
|
# This has to be done here, because Protocol inspects the callstack of __subclasscheck__ to determine
|
|
421
420
|
# whether the subclass check is being called from an isinstance check coming from ABCMeta;
|
|
422
421
|
# see __allow_reckless_class_checks and _ProtocolMeta in typing for details.
|
|
423
422
|
# To align the behavior of ProtocolRegistry and Protocol, __subclasshook__ has to be used.
|
|
424
|
-
|
|
425
|
-
"__subclasshook__"
|
|
426
|
-
)
|
|
427
|
-
if subclasshook is None:
|
|
428
|
-
subclasshook = _lazy_subclass_hook
|
|
429
|
-
else:
|
|
430
|
-
if isinstance(subclasshook, classmethod):
|
|
431
|
-
subclasshook = cast(
|
|
432
|
-
"Callable[[RegistryMeta[T], type], bool]",
|
|
433
|
-
subclasshook.__func__,
|
|
434
|
-
)
|
|
435
|
-
subclasshook = _lazy_subclass_hook_with_pre_hook(subclasshook)
|
|
436
|
-
cls.__subclasshook__ = subclasshook # ty:ignore[invalid-assignment]
|
|
423
|
+
cls.__subclasshook__ = _make_lazy_subclass_hook(namespace.get("__subclasshook__")) # ty:ignore[invalid-assignment]
|
|
437
424
|
|
|
438
425
|
if is_protocol(cls):
|
|
439
426
|
# Disable the gate that prevents Protocols from being checked via isinstance()
|
|
@@ -2,17 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from abc import ABCMeta
|
|
5
6
|
from contextlib import suppress
|
|
6
7
|
from functools import singledispatch, update_wrapper
|
|
7
8
|
from typing import TYPE_CHECKING, Any, SupportsIndex, get_args, overload, override
|
|
8
|
-
from weakref import WeakKeyDictionary
|
|
9
9
|
|
|
10
10
|
from flextype.isinstance import (
|
|
11
11
|
LazyType,
|
|
12
|
-
_find_closest_string_type,
|
|
13
12
|
_is_union_type,
|
|
13
|
+
_module_name_precheck,
|
|
14
|
+
_resolve_loaded_type,
|
|
14
15
|
_split_lazy_type,
|
|
15
|
-
lazy_issubclass,
|
|
16
16
|
)
|
|
17
17
|
from flextype.registry_meta import RegistryMeta
|
|
18
18
|
|
|
@@ -57,14 +57,15 @@ class Flexdispatch[**In, Out]:
|
|
|
57
57
|
__slots__ = (
|
|
58
58
|
"__dict__",
|
|
59
59
|
"__weakref__",
|
|
60
|
-
"_delayed_miss_cache",
|
|
61
|
-
"_delayed_registry_generation",
|
|
62
60
|
"_parse_annotations",
|
|
61
|
+
"_pending_delayed_module_check",
|
|
62
|
+
"_pending_delayed_modules",
|
|
63
|
+
"_pending_module_check",
|
|
64
|
+
"_pending_modules",
|
|
63
65
|
"_singledispatcher",
|
|
64
|
-
"_string_miss_cache",
|
|
65
|
-
"_string_registry_generation",
|
|
66
66
|
"_types_by_func",
|
|
67
67
|
"delayed_registration_registry",
|
|
68
|
+
"delayed_string_registration_registry",
|
|
68
69
|
"dispatch_on",
|
|
69
70
|
"funcname",
|
|
70
71
|
"registry_meta_types",
|
|
@@ -87,28 +88,50 @@ class Flexdispatch[**In, Out]:
|
|
|
87
88
|
self._singledispatcher = singledispatch(func)
|
|
88
89
|
self.funcname = getattr(func, "__name__", "singledispatch function")
|
|
89
90
|
self.string_registry: dict[str, Callable] = {}
|
|
90
|
-
self.
|
|
91
|
+
self.delayed_string_registration_registry: dict[str, RegistrationFunction] = {}
|
|
92
|
+
self.delayed_registration_registry: dict[type, RegistrationFunction] = {}
|
|
91
93
|
self.registry_meta_types: set[RegistryMeta] = set()
|
|
92
94
|
self.dispatch_on: Callable[In, Any] = dispatch_on
|
|
93
95
|
self._parse_annotations = parse_annotations
|
|
94
|
-
self.
|
|
95
|
-
self.
|
|
96
|
-
self.
|
|
97
|
-
self.
|
|
96
|
+
self._pending_modules: set[str] = set()
|
|
97
|
+
self._pending_module_check = _module_name_precheck(self._pending_modules)
|
|
98
|
+
self._pending_delayed_modules: set[str] = set()
|
|
99
|
+
self._pending_delayed_module_check = _module_name_precheck(self._pending_delayed_modules)
|
|
98
100
|
self._types_by_func: dict[Callable, set[type]] = {}
|
|
99
101
|
for registered_type, registered_func in self._singledispatcher.registry.items():
|
|
100
102
|
with suppress(TypeError):
|
|
101
103
|
self._types_by_func.setdefault(registered_func, set()).add(registered_type)
|
|
102
104
|
|
|
103
|
-
def
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
105
|
+
def _resolve_pending_registrations(self) -> None:
|
|
106
|
+
"""Promote available handlers in one pass, after delayed callbacks."""
|
|
107
|
+
pending_modules: set[str] = set()
|
|
108
|
+
for name, func in tuple(self.string_registry.items()):
|
|
109
|
+
unloaded: set[str] = set()
|
|
110
|
+
resolved = _resolve_loaded_type(name, unloaded)
|
|
111
|
+
if isinstance(resolved, type):
|
|
112
|
+
del self.string_registry[name]
|
|
113
|
+
self._eager_register((resolved,), func)
|
|
114
|
+
else:
|
|
115
|
+
pending_modules.update(unloaded)
|
|
116
|
+
self._pending_modules = pending_modules
|
|
117
|
+
self._pending_module_check = _module_name_precheck(self._pending_modules)
|
|
118
|
+
|
|
119
|
+
def _resolve_pending_delayed_registrations(self) -> None:
|
|
120
|
+
"""Promote delayed strings before selecting callbacks, preserving registry order."""
|
|
121
|
+
registry = self.delayed_string_registration_registry
|
|
122
|
+
pending_modules: set[str] = set()
|
|
123
|
+
for target, func in tuple(registry.items()):
|
|
124
|
+
unloaded: set[str] = set()
|
|
125
|
+
resolved = _resolve_loaded_type(target, unloaded)
|
|
126
|
+
if isinstance(resolved, type):
|
|
127
|
+
del registry[target]
|
|
128
|
+
self.delayed_registration_registry[resolved] = func
|
|
129
|
+
else:
|
|
130
|
+
pending_modules.update(unloaded)
|
|
131
|
+
self._pending_delayed_modules = pending_modules
|
|
132
|
+
self._pending_delayed_module_check = _module_name_precheck(pending_modules)
|
|
110
133
|
|
|
111
|
-
def dispatch( # noqa: C901, PLR0912
|
|
134
|
+
def dispatch( # noqa: C901, PLR0912
|
|
112
135
|
self,
|
|
113
136
|
cls: type,
|
|
114
137
|
*,
|
|
@@ -116,45 +139,34 @@ class Flexdispatch[**In, Out]:
|
|
|
116
139
|
registry_meta_lookup: object = NotImplemented,
|
|
117
140
|
) -> Callable[..., Out]:
|
|
118
141
|
"""Find the best available function for the given type or string."""
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
142
|
+
if (
|
|
143
|
+
not self.delayed_string_registration_registry
|
|
144
|
+
and not self.delayed_registration_registry
|
|
145
|
+
and not self.string_registry
|
|
146
|
+
and (registry_meta_lookup is NotImplemented or not self.registry_meta_types)
|
|
147
|
+
):
|
|
148
|
+
return self._singledispatcher.dispatch(cls)
|
|
149
|
+
|
|
150
|
+
if delayed_register:
|
|
151
|
+
if self.delayed_string_registration_registry and self._pending_delayed_module_check():
|
|
152
|
+
self._resolve_pending_delayed_registrations()
|
|
153
|
+
delayed_registration_registry = self.delayed_registration_registry
|
|
154
|
+
if delayed_registration_registry:
|
|
155
|
+
active_registrations = {
|
|
156
|
+
t: func for t, func in delayed_registration_registry.items() if issubclass(cls, t)
|
|
129
157
|
}
|
|
130
|
-
|
|
131
158
|
if active_registrations:
|
|
132
159
|
for registration_func in active_registrations.values():
|
|
133
160
|
registration_func(cls)
|
|
134
|
-
|
|
135
161
|
for t in active_registrations:
|
|
136
162
|
delayed_registration_registry.pop(t, None)
|
|
137
163
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
self._delayed_miss_cache[cls] = delayed_generation
|
|
141
|
-
|
|
142
|
-
if string_registry:
|
|
143
|
-
string_generation = self._string_registry_generation
|
|
144
|
-
string_miss_generation = self._string_miss_cache.get(cls)
|
|
145
|
-
if string_miss_generation != string_generation:
|
|
146
|
-
closest = _find_closest_string_type(cls, string_registry)
|
|
147
|
-
if closest is not None:
|
|
148
|
-
real_type, string_type = closest
|
|
149
|
-
registration_func = string_registry.pop(string_type)
|
|
150
|
-
self._bump_string_registry_generation()
|
|
151
|
-
self._eager_register((real_type,), registration_func)
|
|
152
|
-
else:
|
|
153
|
-
self._string_miss_cache[cls] = string_generation
|
|
164
|
+
if self.string_registry and self._pending_module_check():
|
|
165
|
+
self._resolve_pending_registrations()
|
|
154
166
|
|
|
155
167
|
f = self._singledispatcher.dispatch(cls)
|
|
156
168
|
|
|
157
|
-
if registry_meta_lookup is not NotImplemented:
|
|
169
|
+
if registry_meta_lookup is not NotImplemented and self.registry_meta_types:
|
|
158
170
|
# Check if an instance-level registry registration applies.
|
|
159
171
|
registry_meta_matches: set[type] = set()
|
|
160
172
|
for registry_meta_type in self.registry_meta_types:
|
|
@@ -209,24 +221,33 @@ class Flexdispatch[**In, Out]:
|
|
|
209
221
|
|
|
210
222
|
return f
|
|
211
223
|
|
|
212
|
-
def _eager_register(self, types: tuple[type], func: Callable) -> Callable:
|
|
213
|
-
"""
|
|
214
|
-
|
|
215
|
-
This method simply delegates to the underlying functools.singledispatch instance.
|
|
216
|
-
Instance-based RegistryMeta types and lazy-string registrations are not supported.
|
|
217
|
-
To use the full functionality of flexdispatch, use the `register` method instead.
|
|
218
|
-
"""
|
|
224
|
+
def _eager_register(self, types: tuple[type, ...], func: Callable) -> Callable: # noqa: PLR0912
|
|
225
|
+
"""Register actual classes, batching without duplicating ABC registrations."""
|
|
219
226
|
registry = self._singledispatcher.registry
|
|
220
227
|
old_functions = {t: registry.get(t) for t in types}
|
|
221
228
|
|
|
222
|
-
if len(types)
|
|
223
|
-
|
|
229
|
+
if len(types) <= 2:
|
|
230
|
+
for t in types:
|
|
231
|
+
self._singledispatcher.register(t, func)
|
|
224
232
|
else:
|
|
225
|
-
|
|
226
|
-
|
|
233
|
+
remaining = iter(types)
|
|
234
|
+
union_type = next(remaining)
|
|
235
|
+
# One direct ABC registration enables cache-token tracking for the
|
|
236
|
+
# whole dispatcher; that ABC must not also enter the union.
|
|
237
|
+
if isinstance(union_type, ABCMeta):
|
|
238
|
+
self._singledispatcher.register(union_type, func)
|
|
239
|
+
union_type = next(remaining)
|
|
240
|
+
else:
|
|
241
|
+
for t in remaining:
|
|
242
|
+
if isinstance(t, ABCMeta):
|
|
243
|
+
self._singledispatcher.register(t, func)
|
|
244
|
+
break
|
|
245
|
+
union_type |= t
|
|
246
|
+
# Continue after the first ABC, or with an exhausted iterator if
|
|
247
|
+
# there wasn't one. All remaining classes can join the union.
|
|
248
|
+
for t in remaining:
|
|
227
249
|
union_type |= t
|
|
228
|
-
|
|
229
|
-
|
|
250
|
+
self._singledispatcher.register(union_type, func)
|
|
230
251
|
for t in types:
|
|
231
252
|
if isinstance(t, RegistryMeta):
|
|
232
253
|
self.registry_meta_types.add(t)
|
|
@@ -247,9 +268,9 @@ class Flexdispatch[**In, Out]:
|
|
|
247
268
|
with suppress(TypeError):
|
|
248
269
|
self._types_by_func.setdefault(func, set()).add(t)
|
|
249
270
|
|
|
250
|
-
return
|
|
271
|
+
return func
|
|
251
272
|
|
|
252
|
-
def register(self, cls: LazyType | Callable, func: Callable | None = None) -> Callable:
|
|
273
|
+
def register(self, cls: LazyType | Callable, func: Callable | None = None) -> Callable: # noqa: PLR0912
|
|
253
274
|
"""Register a new implementation for the given type or string."""
|
|
254
275
|
if is_valid_dispatch_type(cls): # ty: ignore[invalid-argument-type]
|
|
255
276
|
if func is None:
|
|
@@ -282,16 +303,19 @@ class Flexdispatch[**In, Out]:
|
|
|
282
303
|
msg = f"Invalid annotation for {argname!r}. {cls!r} is not a class or string."
|
|
283
304
|
raise TypeError(msg)
|
|
284
305
|
|
|
285
|
-
|
|
306
|
+
if self.string_registry and self._pending_module_check():
|
|
307
|
+
self._resolve_pending_registrations()
|
|
308
|
+
pending_modules: set[str] = set()
|
|
309
|
+
types, strings = _split_lazy_type(cls, pending_modules) # ty: ignore[invalid-argument-type]
|
|
286
310
|
|
|
287
|
-
if
|
|
288
|
-
# Use reduce with operator.or_ to dynamically create a Union (PEP 604 style) and avoid private API usage.
|
|
311
|
+
if types:
|
|
289
312
|
self._eager_register(tuple(types), func) # ty:ignore[invalid-argument-type]
|
|
290
313
|
|
|
291
314
|
if len(strings) > 0:
|
|
292
315
|
for s in strings:
|
|
293
316
|
self.string_registry[s] = func # ty: ignore[invalid-assignment]
|
|
294
|
-
self.
|
|
317
|
+
self._pending_modules.update(pending_modules)
|
|
318
|
+
self._pending_module_check = _module_name_precheck(self._pending_modules)
|
|
295
319
|
|
|
296
320
|
return func # ty: ignore[invalid-return-type]
|
|
297
321
|
|
|
@@ -304,7 +328,7 @@ class Flexdispatch[**In, Out]:
|
|
|
304
328
|
@overload
|
|
305
329
|
def delayed_register(self, cls: LazyType, func: RegistrationFunction) -> RegistrationFunction: ...
|
|
306
330
|
|
|
307
|
-
def delayed_register(
|
|
331
|
+
def delayed_register( # noqa: PLR0912
|
|
308
332
|
self,
|
|
309
333
|
cls: LazyType | RegistrationFunction,
|
|
310
334
|
func: RegistrationFunction | None = None,
|
|
@@ -344,16 +368,21 @@ class Flexdispatch[**In, Out]:
|
|
|
344
368
|
msg = f"Invalid annotation for {argname!r}. {cls!r} is not a class or string."
|
|
345
369
|
raise TypeError(msg)
|
|
346
370
|
|
|
347
|
-
|
|
371
|
+
if self.string_registry and self._pending_module_check():
|
|
372
|
+
self._resolve_pending_registrations()
|
|
373
|
+
if self.delayed_string_registration_registry and self._pending_delayed_module_check():
|
|
374
|
+
self._resolve_pending_delayed_registrations()
|
|
375
|
+
pending_modules: set[str] = set()
|
|
376
|
+
types, strings = _split_lazy_type(cls, pending_modules) # ty: ignore[invalid-argument-type]
|
|
348
377
|
|
|
349
378
|
for t in types:
|
|
350
379
|
self.delayed_registration_registry[t] = func # ty: ignore[invalid-assignment]
|
|
351
380
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
self.
|
|
381
|
+
if len(strings) > 0:
|
|
382
|
+
for s in strings:
|
|
383
|
+
self.delayed_string_registration_registry[s] = func # ty: ignore[invalid-assignment]
|
|
384
|
+
self._pending_delayed_modules.update(pending_modules)
|
|
385
|
+
self._pending_delayed_module_check = _module_name_precheck(self._pending_delayed_modules)
|
|
357
386
|
|
|
358
387
|
return func # ty: ignore[invalid-return-type]
|
|
359
388
|
|
|
@@ -362,7 +391,8 @@ class Flexdispatch[**In, Out]:
|
|
|
362
391
|
if not args:
|
|
363
392
|
msg = f"{self.funcname} requires at least 1 positional argument"
|
|
364
393
|
raise TypeError(msg)
|
|
365
|
-
|
|
394
|
+
dispatch_on = self.dispatch_on
|
|
395
|
+
dispatch_value = args[0] if dispatch_on is first_argument else dispatch_on(*args, **kwargs) # ty:ignore[invalid-argument-type]
|
|
366
396
|
return self.dispatch(
|
|
367
397
|
dispatch_value.__class__,
|
|
368
398
|
registry_meta_lookup=dispatch_value,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flextype
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Making types flexible.
|
|
5
5
|
Author-email: Clemens Damke <clemens@cortys.de>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -15,6 +15,7 @@ Classifier: Programming Language :: Python :: 3
|
|
|
15
15
|
Classifier: Programming Language :: Python :: 3.12
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
19
|
Requires-Python: >=3.12.0
|
|
19
20
|
Description-Content-Type: text/markdown
|
|
20
21
|
License-File: LICENSE
|
|
@@ -48,9 +49,22 @@ uv add flextype
|
|
|
48
49
|
|
|
49
50
|
`lazy_isinstance` and `lazy_issubclass` work like `isinstance` and
|
|
50
51
|
`issubclass`, but type references may be real classes, fully qualified string
|
|
51
|
-
names, unions, or tuples. String references are
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
names, unions, or tuples. String references are resolved through `sys.modules`
|
|
53
|
+
and normal attribute lookup, supporting aliases, nested classes and dynamic
|
|
54
|
+
attributes. The resolver does not import missing modules. Unloaded module
|
|
55
|
+
references do not match.
|
|
56
|
+
Resolved references use regular `isinstance` / `issubclass` semantics, including
|
|
57
|
+
virtual subclasses and custom checking hooks, which may also have side effects.
|
|
58
|
+
|
|
59
|
+
Use `"pkg.submodule:Outer.Type"` to specify the module boundary explicitly.
|
|
60
|
+
Resolution waits only for that module; once it is loaded, missing attributes
|
|
61
|
+
raise `AttributeError`. Dotted references such as `"pkg.submodule.Type"` use the
|
|
62
|
+
longest loaded module prefix, even when a shorter module exposes a different
|
|
63
|
+
nested attribute. If lookup fails, they wait only when a longer module prefix
|
|
64
|
+
could still load. Thus `"pkg.C"` raises if `pkg` is loaded but lacks `C`.
|
|
65
|
+
|
|
66
|
+
Lazy and delayed dispatcher registrations follow the same rules. Once a
|
|
67
|
+
reference resolves to a class, later imports do not retarget that registration.
|
|
54
68
|
|
|
55
69
|
```python
|
|
56
70
|
from pathlib import Path
|
|
@@ -206,6 +220,22 @@ registration concept to instance-level registrations. `Registry` and
|
|
|
206
220
|
`RegistryMeta` expose the same mechanism for non-protocol marker classes, and
|
|
207
221
|
the metaclasses are exported too when direct metaclass use is the better fit.
|
|
208
222
|
|
|
223
|
+
Class registries accept the same dotted and `module:qualname` references as
|
|
224
|
+
`flexdispatch`. Available classes are registered immediately; unresolved module
|
|
225
|
+
references are retried on registration, instance checks without a positive
|
|
226
|
+
instance-cache hit, and uncached subclass checks. Resolution registers all
|
|
227
|
+
available references, not just a name matching
|
|
228
|
+
the class being checked. Protocol registries support pending references only
|
|
229
|
+
with `structural_checking=False`; already-loaded string references are eager
|
|
230
|
+
registrations.
|
|
231
|
+
|
|
232
|
+
Subclass checks use the normal ABC cache and hook. Consequently, an alias to a
|
|
233
|
+
class that previously failed a subclass check can remain a cached miss after
|
|
234
|
+
its module loads, until another uncached check or registration triggers
|
|
235
|
+
promotion. Prefer canonical class paths for registrations; aliases are only
|
|
236
|
+
weakly supported. Ordinary `lazy_isinstance` / `lazy_issubclass` lookups remain
|
|
237
|
+
uncached and may use aliases directly.
|
|
238
|
+
|
|
209
239
|
## Development
|
|
210
240
|
|
|
211
241
|
```sh
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
"""A lazy version of isinstance."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from types import UnionType
|
|
6
|
-
from typing import Any, Union, get_args, get_origin
|
|
7
|
-
|
|
8
|
-
type LazyType = type | str | UnionType | tuple[LazyType, ...]
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
def _is_union_type(cls: Any) -> bool: # noqa: ANN401
|
|
12
|
-
return get_origin(cls) in {Union, UnionType}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def _split_lazy_type(lazy_type: LazyType) -> tuple[set[type], set[str]]:
|
|
16
|
-
"""Split classinfo into a set of types and a set of strings."""
|
|
17
|
-
if isinstance(lazy_type, str):
|
|
18
|
-
return set(), {t.strip().removeprefix("builtins.") for t in lazy_type.split("|")}
|
|
19
|
-
if isinstance(lazy_type, type):
|
|
20
|
-
return {lazy_type}, set()
|
|
21
|
-
if isinstance(lazy_type, tuple):
|
|
22
|
-
types: set[type] = set()
|
|
23
|
-
strings: set[str] = set()
|
|
24
|
-
for item in lazy_type:
|
|
25
|
-
t, s = _split_lazy_type(item)
|
|
26
|
-
types.update(t)
|
|
27
|
-
strings.update(s)
|
|
28
|
-
return types, strings
|
|
29
|
-
if _is_union_type(lazy_type):
|
|
30
|
-
types = set()
|
|
31
|
-
strings = set()
|
|
32
|
-
for arg in get_args(lazy_type):
|
|
33
|
-
t, s = _split_lazy_type(arg)
|
|
34
|
-
types.update(t)
|
|
35
|
-
strings.update(s)
|
|
36
|
-
return types, strings
|
|
37
|
-
|
|
38
|
-
msg = f"Invalid classinfo: {lazy_type!r}"
|
|
39
|
-
raise TypeError(msg)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def _find_matching_string_type(cls: type, string_types: set[str] | dict[str, Any]) -> str | None:
|
|
43
|
-
"""Check if the type's name matches any of the strings."""
|
|
44
|
-
module = cls.__module__
|
|
45
|
-
qualname = cls.__qualname__
|
|
46
|
-
|
|
47
|
-
if module == "builtins":
|
|
48
|
-
for s in string_types:
|
|
49
|
-
if qualname == s:
|
|
50
|
-
return s
|
|
51
|
-
|
|
52
|
-
for s in string_types:
|
|
53
|
-
if f"{module}.{qualname}" == s:
|
|
54
|
-
return s
|
|
55
|
-
|
|
56
|
-
return None
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def _find_closest_string_type(cls: type, string_types: set[str] | dict[str, Any]) -> tuple[type, str] | None:
|
|
60
|
-
"""Check if any type in the MRO matches any of the strings."""
|
|
61
|
-
mro = cls.__mro__
|
|
62
|
-
for super_cls in mro:
|
|
63
|
-
matching_type = _find_matching_string_type(super_cls, string_types)
|
|
64
|
-
if matching_type is not None:
|
|
65
|
-
return super_cls, matching_type
|
|
66
|
-
return None
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def lazy_isinstance(obj: object, class_or_tuple: LazyType, /) -> bool:
|
|
70
|
-
"""A lazy version of isinstance."""
|
|
71
|
-
types, strings = _split_lazy_type(class_or_tuple)
|
|
72
|
-
if len(types) > 0 and isinstance(obj, tuple(types)):
|
|
73
|
-
return True
|
|
74
|
-
|
|
75
|
-
if len(strings) > 0:
|
|
76
|
-
return _find_closest_string_type(type(obj), strings) is not None
|
|
77
|
-
|
|
78
|
-
return False
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def lazy_issubclass(cls: type, class_or_tuple: LazyType, /) -> bool:
|
|
82
|
-
"""A lazy version of issubclass."""
|
|
83
|
-
types, strings = _split_lazy_type(class_or_tuple)
|
|
84
|
-
if len(types) > 0 and issubclass(cls, tuple(types)):
|
|
85
|
-
return True
|
|
86
|
-
|
|
87
|
-
if len(strings) > 0:
|
|
88
|
-
return _find_closest_string_type(cls, strings) is not None
|
|
89
|
-
|
|
90
|
-
return False
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|