flextype 0.3.0__tar.gz → 0.4.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.
@@ -0,0 +1,453 @@
1
+ Metadata-Version: 2.4
2
+ Name: flextype
3
+ Version: 0.4.0
4
+ Summary: Making types flexible.
5
+ Author-email: Clemens Damke <clemens@cortys.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: source, https://github.com/Cortys/flextype
8
+ Project-URL: tracker, https://github.com/Cortys/flextype/issues
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: Microsoft :: Windows
12
+ Classifier: Operating System :: Unix
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Requires-Python: >=3.12.0
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: typing-extensions>=4.7.0; python_version < "3.13"
23
+ Dynamic: license-file
24
+
25
+ <div align="center">
26
+ <picture>
27
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Cortys/flextype/master/docs/source/_static/logo/flextype-logo-horizontal-dark.svg">
28
+ <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/Cortys/flextype/master/docs/source/_static/logo/flextype-logo-horizontal-light.svg">
29
+ <img alt="flextype" src="https://raw.githubusercontent.com/Cortys/flextype/master/docs/source/_static/logo/flextype-logo-horizontal-light.svg" width="320">
30
+ </picture>
31
+ </div>
32
+
33
+ `flextype` makes Python types more flexible:
34
+
35
+ - **Lazy type checks & dispatch** (`lazy_isinstance`, `flexdispatch`): match types by name without importing optional dependencies.
36
+ - **Ranked casting & autocasting** (`cast`, `autocast`, `flexdispatch(autocast=True)`): chain conversions, decline values dynamically, and refine objects automatically.
37
+ - **Instance-level registries** (`ProtocolRegistry`, `Registry`): classify individual objects dynamically without altering their inheritance hierarchy.
38
+
39
+ ## Install
40
+
41
+ Requires Python 3.12+.
42
+
43
+ ```sh
44
+ pip install flextype
45
+ # or
46
+ uv add flextype
47
+ ```
48
+
49
+ ## Lazy Type Checking
50
+
51
+ `lazy_isinstance` and `lazy_issubclass` work like `isinstance` and `issubclass`,
52
+ but also accept dotted strings, explicit `"module:QualName"` strings, tuples, and
53
+ unions. Missing modules are never imported and simply do not match.
54
+
55
+ ```python
56
+ from pathlib import Path
57
+
58
+ from flextype import lazy_isinstance, lazy_issubclass
59
+
60
+ path = Path("README.md")
61
+
62
+ assert lazy_isinstance(path, "pathlib.Path")
63
+ assert lazy_isinstance(path, "pathlib:Path")
64
+ assert lazy_isinstance(path, (Path, "os.PathLike"))
65
+ assert lazy_issubclass(type(path), ("pathlib.Path", str))
66
+ assert not lazy_isinstance(path, "not_installed_pkg.Thing")
67
+ ```
68
+
69
+ Once a referenced module *is* loaded, normal `isinstance`/`issubclass` rules
70
+ apply (including virtual ABCs), and missing attributes raise `AttributeError`.
71
+
72
+ ## `flexdispatch`
73
+
74
+ `flexdispatch` is a lazy alternative to `functools.singledispatch` that supports
75
+ string type names and on-demand handler loading.
76
+
77
+ ```python
78
+ from pathlib import Path
79
+
80
+ from flextype import flexdispatch
81
+
82
+
83
+ @flexdispatch
84
+ def render(value: object) -> str:
85
+ return repr(value)
86
+
87
+
88
+ @render.register("pathlib.Path")
89
+ def render_path(value: object) -> str:
90
+ return f"path: {value}"
91
+
92
+
93
+ assert render(Path("README.md")) == "path: README.md"
94
+ assert render(42) == "42"
95
+ ```
96
+
97
+ Use `delayed_register` when the handler itself lives in an optional integration
98
+ module—it imports that module only when a matching type is first dispatched:
99
+
100
+ ```python
101
+ # myapp/render.py
102
+ @render.delayed_register("pandas.DataFrame")
103
+ def _load_pandas(seen_type: type) -> None:
104
+ import myapp.pandas_render # registers @render.register(pd.DataFrame)
105
+ ```
106
+
107
+ For dispatchers that should automatically convert unmatched inputs, see
108
+ [Autocasting in `flexdispatch`](#autocasting-in-flexdispatch) below.
109
+
110
+ ## Casting
111
+
112
+ ### Registering & chaining casts
113
+
114
+ Register conversions with `@caster` (inferring types from annotations, or
115
+ passing them explicitly) or `@castmethod` inside a class. `cast` finds the
116
+ lowest-cost chain between types.
117
+
118
+ ```python
119
+ from flextype.cast import cast, caster, castmethod
120
+
121
+
122
+ @caster
123
+ def to_float(value: int) -> float:
124
+ return float(value)
125
+
126
+
127
+ @caster(cost=1)
128
+ def to_str(value: float | bytes) -> str:
129
+ return value.decode() if isinstance(value, bytes) else f"{value:.1f}"
130
+
131
+
132
+ class Message:
133
+ @castmethod
134
+ def text(self) -> str:
135
+ return "hello"
136
+
137
+
138
+ assert cast(4, str) == "4.0" # chained: int -> float -> str
139
+ assert cast(b"hi", str) == "hi" # union source
140
+ assert cast(Message(), str) == "hello" # @castmethod
141
+
142
+ to_text = cast(str, default="n/a") # curried callable with fallback
143
+ assert to_text(4) == "4.0"
144
+ assert to_text(object()) == "n/a"
145
+ ```
146
+
147
+ ### Value-dependent casts & fallback
148
+
149
+ A conversion can raise `CastUnavailable` when it doesn't apply to a particular
150
+ instance. `cast` automatically tries the next-best route; if all routes decline,
151
+ it raises a `CastUnavailableGroup` listing every attempted route.
152
+
153
+ ```python
154
+ from decimal import Decimal
155
+
156
+ from flextype.cast import CastUnavailable, cast, caster, try_cast
157
+
158
+
159
+ @caster
160
+ def exact_int(value: float) -> int:
161
+ if not value.is_integer():
162
+ raise CastUnavailable("not integral")
163
+ return int(value)
164
+
165
+
166
+ @caster(cost=1)
167
+ def to_decimal(value: float) -> Decimal:
168
+ return Decimal(str(value))
169
+
170
+
171
+ @caster
172
+ def round_decimal(value: Decimal) -> int:
173
+ return round(value)
174
+
175
+
176
+ assert cast(4.0, int) == 4 # exact_int succeeds (cost 0)
177
+ assert cast(4.6, int) == 5 # exact_int declines -> falls back to float -> Decimal -> int
178
+
179
+ result = try_cast(4.0, int) # CastResult(value=4, caster=...) or None
180
+ assert result is not None and result.value == 4
181
+ ```
182
+
183
+ - `cast(value, target, default=...)` returns `default` on `CastUnavailable`.
184
+ - `try_cast(value, target)` returns `CastResult(value, caster)` or `None`
185
+ (useful when `None` is a valid cast result or you want to inspect `.caster`).
186
+ - Non-`CastUnavailable` exceptions (e.g. `ValueError`) propagate immediately.
187
+
188
+ ### Multiple targets & wrapper annotations
189
+
190
+ Pass a union (`B | C`) or tuple (`(B, C)`) as the target. Routes rank by
191
+ `(cost, target_index, -specificity, mro_distance, chain_length)`: lower cost
192
+ always wins; at equal cost, nominal subclasses beat superclasses regardless of
193
+ target order, and unrelated targets break ties by their given order. Already
194
+ compatible inputs return unchanged.
195
+
196
+ ```python
197
+ from typing import Annotated
198
+
199
+ from flextype import cast, caster, register_type_unwrapper
200
+
201
+
202
+ class Animal: ...
203
+ class Dog(Animal): ...
204
+ class Cat(Animal): ...
205
+
206
+
207
+ caster(str, Animal, lambda _: Animal())
208
+ caster(str, Dog, lambda _: Dog())
209
+
210
+ assert type(cast("rex", Animal)) is Dog # subclass Dog beats Animal at equal cost
211
+ assert type(cast("rex", (Animal, Cat))) is Dog
212
+ assert cast(4, Annotated[str, "label"]) == "4.0"
213
+ ```
214
+
215
+ `Annotated`, `TypeAliasType`, `NewType`, qualifiers (`Final`, `ReadOnly`, …),
216
+ generic origins (`list[int]` → `list`), and `jaxtyping` array annotations unwrap
217
+ to their underlying runtime types automatically in both `cast` and
218
+ `flexdispatch`. Use `@register_type_unwrapper` to teach both about custom
219
+ wrapper annotations:
220
+
221
+ ```python
222
+ @register_type_unwrapper
223
+ def unwrap_custom(ann: object) -> object | None:
224
+ return getattr(ann, "__wrapped_type__", None)
225
+ ```
226
+
227
+ ### Autocasting
228
+
229
+ #### Constructor autocasting
230
+
231
+ Use `metaclass=autocast(*targets)` to refine newly constructed objects into a
232
+ proper subclass via the active cast graph:
233
+
234
+ ```python
235
+ from abc import ABC, abstractmethod
236
+
237
+ from flextype.autocast import autocast
238
+ from flextype.cast import CastUnavailable, caster
239
+
240
+
241
+ class KeyLookup(ABC):
242
+ @abstractmethod
243
+ def by_key(self, key: str) -> int: ...
244
+
245
+
246
+ class Entries(metaclass=autocast(KeyLookup)):
247
+ def __init__(self, items: tuple[tuple[str, int], ...]) -> None:
248
+ self.items = items
249
+
250
+
251
+ class _IndexedEntries(Entries, KeyLookup):
252
+ def __init__(self, items: tuple[tuple[str, int], ...], index: dict[str, int]) -> None:
253
+ super().__init__(items)
254
+ self._index = index
255
+
256
+ def by_key(self, key: str) -> int:
257
+ return self._index[key]
258
+
259
+
260
+ @caster
261
+ def index_entries(source: Entries) -> KeyLookup:
262
+ index = dict(source.items)
263
+ if len(index) != len(source.items):
264
+ raise CastUnavailable("duplicate keys")
265
+ return _IndexedEntries(source.items, index)
266
+
267
+
268
+ indexed = Entries((("a", 1), ("b", 2)))
269
+ assert isinstance(indexed, KeyLookup) and indexed.by_key("b") == 2
270
+
271
+ plain = Entries((("a", 1), ("a", 2))) # declined -> stays Entries
272
+ assert type(plain) is Entries
273
+ ```
274
+
275
+ By default, constructor autocasting uses `max_cost=inf`, `max_mro_distance=0`,
276
+ and `max_chain_length=1`. Pass those kwargs to `autocast(...)` to widen them, or
277
+ use `metaclass=autocast()` on a subclass to disable inherited refinement. A
278
+ replacement must be a proper nominal subclass of the constructed class.
279
+
280
+ #### Autocasting in `flexdispatch`
281
+
282
+ Pass `autocast=True` to `flexdispatch` so unmatched inputs are automatically
283
+ cast to the best registered handler before falling back to the default `object`
284
+ implementation:
285
+
286
+ ```python
287
+ from flextype import flexdispatch
288
+ from flextype.cast import CastUnavailable, caster
289
+
290
+
291
+ class Raw:
292
+ def __init__(self, text: str) -> None:
293
+ self.text = text
294
+
295
+
296
+ class Document:
297
+ def __init__(self, text: str) -> None:
298
+ self.text = text
299
+
300
+
301
+ class JsonDocument(Document): ...
302
+
303
+
304
+ @caster
305
+ def parse_json(raw: Raw) -> JsonDocument:
306
+ if not raw.text.startswith("{"):
307
+ raise CastUnavailable("not JSON")
308
+ return JsonDocument(raw.text)
309
+
310
+
311
+ @caster
312
+ def parse_text(raw: Raw) -> Document:
313
+ return Document(raw.text)
314
+
315
+
316
+ @flexdispatch(autocast=True)
317
+ def process(doc: object) -> str:
318
+ return f"unknown:{doc}"
319
+
320
+
321
+ @process.register(Document)
322
+ def _process_doc(doc: Document) -> str:
323
+ return f"doc:{doc.text}"
324
+
325
+
326
+ @process.register(JsonDocument)
327
+ def _process_json(doc: JsonDocument) -> str:
328
+ return f"json:{doc.text}"
329
+
330
+
331
+ assert process(Raw('{"a": 1}')) == 'json:{"a": 1}' # prefers subclass JsonDocument
332
+ assert process(Raw("hello")) == "doc:hello" # falls back to Document
333
+ assert process(123) == "unknown:123" # no caster -> default handler
334
+ ```
335
+
336
+ Like class `autocast`, `flexdispatch` accepts `max_cost=inf`,
337
+ `max_mro_distance=0`, and `max_chain_length=1`. Direct, subclass, ABC, and
338
+ registry hits bypass casting completely; lazy string and delayed registrations
339
+ resolve before target selection.
340
+
341
+ ### Universal casters
342
+
343
+ Use `@universal_caster` (or `@universal_castmethod`) for generic wrappers that
344
+ delegate conversion to the requested target type while honoring remaining
345
+ budgets:
346
+
347
+ ```python
348
+ from dataclasses import dataclass
349
+ from typing import Unpack
350
+
351
+ from flextype.cast import CastLimits, cast, universal_caster
352
+
353
+
354
+ @dataclass
355
+ class Wrapped:
356
+ value: object
357
+
358
+
359
+ @universal_caster(cost=1, target_bound=object)
360
+ def unwrap[T](value: Wrapped, target: type[T], **limits: Unpack[CastLimits]) -> T:
361
+ return cast(value.value, target, **limits)
362
+
363
+
364
+ assert cast(Wrapped(4), str, max_cost=2, max_chain_length=3) == "4.0"
365
+ ```
366
+
367
+ Universal casters are terminal steps (tried after finite-cost ordinary routes
368
+ when `max_cost` is unbounded), filtered by `target_bound`, and guarded against
369
+ infinite recursion on the same `(graph, value, target)`.
370
+
371
+ ### Inspecting routes & scoped graphs
372
+
373
+ ```python
374
+ from flextype.cast import CASTS, CasterGraph, iter_casters, reachable
375
+
376
+ assert reachable(int, str)
377
+ routes = list(iter_casters(int, str, max_cost=2, max_chain_length=3))
378
+
379
+ # Isolate registrations in a custom graph (or bind one via CASTS.set(graph))
380
+ graph = CasterGraph()
381
+ ```
382
+
383
+ ## Instance-Level Registries
384
+
385
+ `ProtocolRegistry` and `Registry` extend ABC registration to individual
386
+ instances—either explicitly via `register_instance` or dynamically via
387
+ `__instancehook__`—and integrate directly with `flexdispatch`.
388
+
389
+ ```python
390
+ from flextype import ProtocolRegistry, flexdispatch
391
+
392
+
393
+ class Verified(ProtocolRegistry, structural_checking=False):
394
+ pass
395
+
396
+
397
+ class IntList(ProtocolRegistry, structural_checking=False):
398
+ @classmethod
399
+ def __instancehook__(cls, instance: object, /) -> bool:
400
+ return isinstance(instance, list) and all(isinstance(x, int) for x in instance)
401
+
402
+
403
+ @flexdispatch
404
+ def handle(value: object) -> str:
405
+ return "default"
406
+
407
+
408
+ @handle.register(Verified)
409
+ def _handle_verified(value: Verified) -> str:
410
+ return "verified"
411
+
412
+
413
+ @handle.register(IntList)
414
+ def _handle_ints(value: list[int]) -> str:
415
+ return f"sum={sum(value)}"
416
+
417
+
418
+ class Doc: ...
419
+
420
+
421
+ draft, release = Doc(), Doc()
422
+ Verified.register_instance(release)
423
+
424
+ assert handle(draft) == "default"
425
+ assert handle(release) == "verified"
426
+ assert handle([1, 2, 3]) == "sum=6"
427
+ assert handle([1, "2"]) == "default"
428
+ ```
429
+
430
+ Pass `structural_checking=False` on `ProtocolRegistry` to opt out of standard
431
+ structural protocol matching and rely only on inheritance, registrations, and
432
+ `__instancehook__` (return `NotImplemented` from `__instancehook__` to fall
433
+ through). `Registry` and `RegistryMeta` provide the same mechanism without
434
+ `Protocol`.
435
+
436
+ ## Development
437
+
438
+ ```sh
439
+ uv run ruff check
440
+ uv run ty check
441
+ uv run pytest
442
+ ```
443
+
444
+ Pre-commit hooks are managed with `prek`:
445
+
446
+ ```sh
447
+ uv run prek install
448
+ uv run prek run --all-files
449
+ ```
450
+
451
+ ## License
452
+
453
+ This project is licensed under the Apache License 2.0.