flextype 0.1.2__tar.gz → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flextype
3
- Version: 0.1.2
3
+ Version: 0.3.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 matched against the actual
52
- runtime type name, so optional dependencies do not need to be imported just to
53
- perform a check.
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
@@ -122,6 +136,88 @@ def render_dataframe(value: pd.DataFrame) -> str:
122
136
  The delayed callback receives the concrete matching type and runs once. After
123
137
  the import, dispatch uses the regular `pd.DataFrame` registration.
124
138
 
139
+ ### Casting
140
+
141
+ `caster` registers conversions using the first positional parameter's annotation
142
+ and the return annotation. Use it directly or configure its cost and graph:
143
+
144
+ ```python
145
+ from flextype.cast import cast, caster
146
+
147
+
148
+ @caster
149
+ def stringify(value: int) -> str:
150
+ return str(value)
151
+
152
+
153
+ @caster(cost=1)
154
+ def decode(value: bytes | bytearray) -> str:
155
+ return value.decode()
156
+
157
+
158
+ assert cast(4, str) == "4"
159
+ assert cast(b"hello", str) == "hello"
160
+
161
+ to_str = cast(str)
162
+ assert to_str(4) == "4"
163
+ assert to_str(b"hello") == "hello"
164
+ ```
165
+
166
+ With one positional argument, `cast(target)` returns a callable accepting a value.
167
+ It preserves any explicit `graph` and `max_*` limits; otherwise, it uses the active
168
+ graph when the callable is invoked. `graph.cast(target)` supports the same form.
169
+
170
+ Explicit types are also supported: `caster(int, str, stringify)` or
171
+ `@caster((bytes, bytearray), str)`. Unions and tuples register every source/target
172
+ combination with the same function. Parameterized types such as `list[int]` are
173
+ registered against their runtime origin (`list`).
174
+
175
+ All registration forms return the original function unchanged. Registered caster
176
+ metadata remains available through `CasterGraph.get_direct_caster`.
177
+ Costs must be nonnegative and not NaN; positive infinity is allowed.
178
+
179
+ Use `castmethod` inside a class to register an instance method. The source is
180
+ always the defining class; the target is inferred from the return annotation or
181
+ given explicitly. Cost, graph, unions, tuples, and generic origins work as with
182
+ `caster`:
183
+
184
+ ```python
185
+ from flextype.cast import cast, castmethod
186
+
187
+
188
+ class Message:
189
+ @castmethod
190
+ def text(self) -> str:
191
+ return "hello"
192
+
193
+ @castmethod(bytes, cost=1)
194
+ def encode(self):
195
+ return self.text().encode()
196
+
197
+
198
+ assert cast(Message(), str) == "hello"
199
+ assert cast(Message(), bytes) == b"hello"
200
+ ```
201
+
202
+ Registration happens during class creation and preserves normal method binding.
203
+ `castmethod` is intended for instance methods in class bodies: decoration outside
204
+ a class does not register a cast on its own. No source argument is accepted.
205
+ Inferred annotation names resolve against module globals and the owning class
206
+ namespace; otherwise, pass locally scoped target types explicitly.
207
+
208
+ `get_caster(source, target, graph=...)` returns the best caster without executing
209
+ it. Like `cast`, it uses the active graph when `graph` is omitted and accepts all
210
+ three `max_*` limits.
211
+
212
+ Use `graph.get_reachable_casters(source, max_cost=..., max_mro_distance=...,
213
+ max_chain_length=...)` to map reachable registered target types to their best
214
+ casters. Ranking and inclusive limits are the same as `graph.get_caster`.
215
+
216
+ For a quick, unconstrained check, `graph.get_reachable_types(source)` returns a
217
+ set of reachable registered target types without ranking or constructing casts.
218
+ Pass an optional `target` to stop as soon as a compatible type is found; that
219
+ target is included on success, but the remaining results may be incomplete.
220
+
125
221
  ### Registries
126
222
 
127
223
  `ProtocolRegistry` is useful for defining marker types: runtime-only semantic
@@ -206,6 +302,22 @@ registration concept to instance-level registrations. `Registry` and
206
302
  `RegistryMeta` expose the same mechanism for non-protocol marker classes, and
207
303
  the metaclasses are exported too when direct metaclass use is the better fit.
208
304
 
305
+ Class registries accept the same dotted and `module:qualname` references as
306
+ `flexdispatch`. Available classes are registered immediately; unresolved module
307
+ references are retried on registration, instance checks without a positive
308
+ instance-cache hit, and uncached subclass checks. Resolution registers all
309
+ available references, not just a name matching
310
+ the class being checked. Protocol registries support pending references only
311
+ with `structural_checking=False`; already-loaded string references are eager
312
+ registrations.
313
+
314
+ Subclass checks use the normal ABC cache and hook. Consequently, an alias to a
315
+ class that previously failed a subclass check can remain a cached miss after
316
+ its module loads, until another uncached check or registration triggers
317
+ promotion. Prefer canonical class paths for registrations; aliases are only
318
+ weakly supported. Ordinary `lazy_isinstance` / `lazy_issubclass` lookups remain
319
+ uncached and may use aliases directly.
320
+
209
321
  ## Development
210
322
 
211
323
  ```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 matched against the actual
29
- runtime type name, so optional dependencies do not need to be imported just to
30
- perform a check.
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
@@ -99,6 +112,88 @@ def render_dataframe(value: pd.DataFrame) -> str:
99
112
  The delayed callback receives the concrete matching type and runs once. After
100
113
  the import, dispatch uses the regular `pd.DataFrame` registration.
101
114
 
115
+ ### Casting
116
+
117
+ `caster` registers conversions using the first positional parameter's annotation
118
+ and the return annotation. Use it directly or configure its cost and graph:
119
+
120
+ ```python
121
+ from flextype.cast import cast, caster
122
+
123
+
124
+ @caster
125
+ def stringify(value: int) -> str:
126
+ return str(value)
127
+
128
+
129
+ @caster(cost=1)
130
+ def decode(value: bytes | bytearray) -> str:
131
+ return value.decode()
132
+
133
+
134
+ assert cast(4, str) == "4"
135
+ assert cast(b"hello", str) == "hello"
136
+
137
+ to_str = cast(str)
138
+ assert to_str(4) == "4"
139
+ assert to_str(b"hello") == "hello"
140
+ ```
141
+
142
+ With one positional argument, `cast(target)` returns a callable accepting a value.
143
+ It preserves any explicit `graph` and `max_*` limits; otherwise, it uses the active
144
+ graph when the callable is invoked. `graph.cast(target)` supports the same form.
145
+
146
+ Explicit types are also supported: `caster(int, str, stringify)` or
147
+ `@caster((bytes, bytearray), str)`. Unions and tuples register every source/target
148
+ combination with the same function. Parameterized types such as `list[int]` are
149
+ registered against their runtime origin (`list`).
150
+
151
+ All registration forms return the original function unchanged. Registered caster
152
+ metadata remains available through `CasterGraph.get_direct_caster`.
153
+ Costs must be nonnegative and not NaN; positive infinity is allowed.
154
+
155
+ Use `castmethod` inside a class to register an instance method. The source is
156
+ always the defining class; the target is inferred from the return annotation or
157
+ given explicitly. Cost, graph, unions, tuples, and generic origins work as with
158
+ `caster`:
159
+
160
+ ```python
161
+ from flextype.cast import cast, castmethod
162
+
163
+
164
+ class Message:
165
+ @castmethod
166
+ def text(self) -> str:
167
+ return "hello"
168
+
169
+ @castmethod(bytes, cost=1)
170
+ def encode(self):
171
+ return self.text().encode()
172
+
173
+
174
+ assert cast(Message(), str) == "hello"
175
+ assert cast(Message(), bytes) == b"hello"
176
+ ```
177
+
178
+ Registration happens during class creation and preserves normal method binding.
179
+ `castmethod` is intended for instance methods in class bodies: decoration outside
180
+ a class does not register a cast on its own. No source argument is accepted.
181
+ Inferred annotation names resolve against module globals and the owning class
182
+ namespace; otherwise, pass locally scoped target types explicitly.
183
+
184
+ `get_caster(source, target, graph=...)` returns the best caster without executing
185
+ it. Like `cast`, it uses the active graph when `graph` is omitted and accepts all
186
+ three `max_*` limits.
187
+
188
+ Use `graph.get_reachable_casters(source, max_cost=..., max_mro_distance=...,
189
+ max_chain_length=...)` to map reachable registered target types to their best
190
+ casters. Ranking and inclusive limits are the same as `graph.get_caster`.
191
+
192
+ For a quick, unconstrained check, `graph.get_reachable_types(source)` returns a
193
+ set of reachable registered target types without ranking or constructing casts.
194
+ Pass an optional `target` to stop as soon as a compatible type is found; that
195
+ target is included on success, but the remaining results may be incomplete.
196
+
102
197
  ### Registries
103
198
 
104
199
  `ProtocolRegistry` is useful for defining marker types: runtime-only semantic
@@ -183,6 +278,22 @@ registration concept to instance-level registrations. `Registry` and
183
278
  `RegistryMeta` expose the same mechanism for non-protocol marker classes, and
184
279
  the metaclasses are exported too when direct metaclass use is the better fit.
185
280
 
281
+ Class registries accept the same dotted and `module:qualname` references as
282
+ `flexdispatch`. Available classes are registered immediately; unresolved module
283
+ references are retried on registration, instance checks without a positive
284
+ instance-cache hit, and uncached subclass checks. Resolution registers all
285
+ available references, not just a name matching
286
+ the class being checked. Protocol registries support pending references only
287
+ with `structural_checking=False`; already-loaded string references are eager
288
+ registrations.
289
+
290
+ Subclass checks use the normal ABC cache and hook. Consequently, an alias to a
291
+ class that previously failed a subclass check can remain a cached miss after
292
+ its module loads, until another uncached check or registration triggers
293
+ promotion. Prefer canonical class paths for registrations; aliases are only
294
+ weakly supported. Ordinary `lazy_isinstance` / `lazy_issubclass` lookups remain
295
+ uncached and may use aliases directly.
296
+
186
297
  ## Development
187
298
 
188
299
  ```sh
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "flextype"
7
- version = "0.1.2"
7
+ version = "0.3.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.16.1",
41
- "ty>=0.0.65",
41
+ "ruff>=0.17.1",
42
+ "ty>=0.0.89",
42
43
  ]
43
44
  test = [
44
45
  "pytest>=8.0",
@@ -14,6 +14,7 @@ from .registry_meta import (
14
14
  get_explicit_registry_classes,
15
15
  )
16
16
  from .singledispatch import Flexdispatch, flexdispatch, is_valid_dispatch_type
17
+ from .switchdispatch import switch, switchdispatch
17
18
 
18
19
  __all__ = [
19
20
  "Flexdispatch",
@@ -33,4 +34,6 @@ __all__ = [
33
34
  "lazy_isinstance",
34
35
  "lazy_issubclass",
35
36
  "registry_pickle",
37
+ "switch",
38
+ "switchdispatch",
36
39
  ]