Skip to content

Commit acf92d2

Browse files
authored
Fix annotated (#419)
* Fix annotated * Fix for 3.8
1 parent acd3d10 commit acf92d2

3 files changed

Lines changed: 13 additions & 8 deletions

File tree

HISTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
([#408](https://github.com/python-attrs/cattrs/pull/408))
3535
- Fix structuring `Final` lists.
3636
([#412](https://github.com/python-attrs/cattrs/issues/412))
37+
- Fix certain cases of structuring `Annotated` types.
38+
([#418](https://github.com/python-attrs/cattrs/issues/418))
3739

3840

3941
## 23.1.2 (2023-06-02)

src/cattrs/converters.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -917,9 +917,11 @@ def gen_unstructure_annotated(self, type):
917917
origin = type.__origin__
918918
return self._unstructure_func.dispatch(origin)
919919

920-
def gen_structure_annotated(self, type):
920+
def gen_structure_annotated(self, type) -> Callable:
921+
"""A hook factory for annotated types."""
921922
origin = type.__origin__
922-
return self._structure_func.dispatch(origin)
923+
hook = self._structure_func.dispatch(origin)
924+
return lambda v, _: hook(v, origin)
923925

924926
def gen_unstructure_typeddict(self, cl: Any) -> Callable[[Dict], Dict]:
925927
"""Generate a TypedDict unstructure function.

tests/test_converter.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -671,21 +671,22 @@ class Inner:
671671
class Outer:
672672
i: Annotated[Inner, "test"]
673673
j: List[Annotated[Inner, "test"]]
674+
k: Annotated[Union[Inner, None], "test"]
674675

675-
orig = Outer(Inner(1), [Inner(1)])
676+
orig = Outer(Inner(1), [Inner(1)], Inner(1))
676677
raw = converter.unstructure(orig)
677678

678-
assert raw == {"i": {"a": 1}, "j": [{"a": 1}]}
679+
assert raw == {"i": {"a": 1}, "j": [{"a": 1}], "k": {"a": 1}}
679680

680681
structured = converter.structure(raw, Outer)
681682
assert structured == orig
682683

683684
# Now register a hook and rerun the test.
684-
converter.register_unstructure_hook(Inner, lambda v: {"a": 2})
685+
converter.register_unstructure_hook(Inner, lambda _: {"a": 2})
685686

686-
raw = converter.unstructure(Outer(Inner(1), [Inner(1)]))
687+
raw = converter.unstructure(Outer(Inner(1), [Inner(1)], Inner(1)))
687688

688-
assert raw == {"i": {"a": 2}, "j": [{"a": 2}]}
689+
assert raw == {"i": {"a": 2}, "j": [{"a": 2}], "k": {"a": 2}}
689690

690691
structured = converter.structure(raw, Outer)
691-
assert structured == Outer(Inner(2), [Inner(2)])
692+
assert structured == Outer(Inner(2), [Inner(2)], Inner(2))

0 commit comments

Comments
 (0)