Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ Our backwards-compatibility policy can be found [here](https://github.com/python

## NEXT

- Fix {meth}`BaseConverter.register_structure_hook` raising `TypeError` for `ForwardRef` targets. Registered hooks also match equivalent forward references.
([#206](https://github.com/python-cattrs/cattrs/issues/206))
- Fix the msgspec converter passing typed deques directly to the encoder, which cannot serialize them. Deques are now unstructured into lists, including when nested in attrs classes or dataclasses.
([#818](https://github.com/python-attrs/cattrs/issues/818) [#819](https://github.com/python-attrs/cattrs/pull/819))

Expand Down
6 changes: 5 additions & 1 deletion src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from inspect import Signature
from inspect import signature as inspect_signature
from pathlib import Path
from typing import Any, Optional, Tuple, TypeVar, overload
from typing import Any, ForwardRef, Optional, Tuple, TypeVar, overload

from attrs import Attribute, resolve_types
from attrs import has as attrs_has
Expand Down Expand Up @@ -556,6 +556,10 @@ def register_structure_hook(
elif get_newtype_base(cl) is not None:
# This is a newtype, so we handle it specially.
self._structure_func.register_func_list([(lambda t: t is cl, func)])
elif isinstance(cl, ForwardRef) or (
AnnotationForwardRef is not None and isinstance(cl, AnnotationForwardRef)
):
self._structure_func.register_func_list([(lambda t: t == cl, func)])
else:
self._structure_func.register_cls_list([(cl, func)])
return None
Expand Down
18 changes: 18 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Annotated,
Any,
Deque,
ForwardRef,
FrozenSet,
List,
MutableSequence,
Expand Down Expand Up @@ -836,6 +837,23 @@ def my_structure_hook(value, _) -> Test:
assert converter.structure({"a": 5}, Test) == Test(6)


@pytest.mark.parametrize("use_decorator", [False, True], ids=["explicit", "decorator"])
def test_register_structure_hook_for_forward_ref(
converter: BaseConverter, use_decorator: bool
):
target = ForwardRef("CustomType")

def structure_hook(value, _) -> target:
return int(value) + 1

if use_decorator:
assert converter.register_structure_hook(structure_hook) is structure_hook
else:
converter.register_structure_hook(target, structure_hook)

assert converter.structure("41", ForwardRef("CustomType")) == 42


def test_hook_factory_decorators(converter: BaseConverter):
"""Hook factory decorators work."""

Expand Down