|
14 | 14 | NamedTuple, |
15 | 15 | Optional, |
16 | 16 | Tuple, |
| 17 | + TypeAliasType, |
17 | 18 | Union, |
18 | 19 | get_args, |
19 | 20 | get_origin, |
@@ -289,6 +290,10 @@ def load(self, dct: str): |
289 | 290 |
|
290 | 291 |
|
291 | 292 | def build_schema(Type) -> Schema: |
| 293 | + if isinstance(Type, TypeAliasType): |
| 294 | + # handle 'type ... = ...' aliases |
| 295 | + Type = Type.__value__ |
| 296 | + |
292 | 297 | # just to avoid confusion in case of weirdness with stringish type annotations |
293 | 298 | assert not isinstance(Type, str), Type |
294 | 299 |
|
@@ -414,6 +419,13 @@ def normalise(x): |
414 | 419 | return (j, obj2) |
415 | 420 |
|
416 | 421 |
|
| 422 | +## this is used for test below... |
| 423 | +# however if we define this inside the test function, it fails if from __future__ import annotations is present on the file.. |
| 424 | +type _IntType = int |
| 425 | +type _StrIntType = str | int |
| 426 | +## |
| 427 | + |
| 428 | + |
417 | 429 | # TODO customise with cattrs |
418 | 430 | def test_serialize_and_deserialize() -> None: |
419 | 431 | import pytest |
@@ -504,6 +516,22 @@ class WithJson: |
504 | 516 | id: int |
505 | 517 | raw_data: dict[str, Any] |
506 | 518 |
|
| 519 | + ## type aliases including new 3.12 type aliases |
| 520 | + # this works.. |
| 521 | + StrInt = str | int |
| 522 | + helper('aaa', StrInt) |
| 523 | + |
| 524 | + helper('aaa', _StrIntType) |
| 525 | + helper([1, 2, 3], list[_IntType]) |
| 526 | + |
| 527 | + @dataclass |
| 528 | + class TestTypeAlias: |
| 529 | + x: _IntType |
| 530 | + value: _StrIntType |
| 531 | + |
| 532 | + helper(TestTypeAlias(x=1, value='aaa'), TestTypeAlias) |
| 533 | + ## |
| 534 | + |
507 | 535 | # json-ish stuff |
508 | 536 | helper({}, dict[str, Any]) |
509 | 537 | helper(WithJson(id=123, raw_data={'payload': 'whatever', 'tags': ['a', 'b', 'c']}), WithJson) |
|
0 commit comments