From d67982e04d0144e9e0bf1d974de904f519c25ba6 Mon Sep 17 00:00:00 2001 From: Vinayak Deshmuk <118991845+Vinayak19112003@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:11:59 +0000 Subject: [PATCH] Fix registering structure hooks for forward references Signed-off-by: Vinayak Deshmuk <118991845+Vinayak19112003@users.noreply.github.com> --- HISTORY.md | 2 ++ src/cattrs/converters.py | 6 +++++- tests/test_converter.py | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/HISTORY.md b/HISTORY.md index 942616e3..961beb70 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -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)) diff --git a/src/cattrs/converters.py b/src/cattrs/converters.py index 70c19b44..21ecfb33 100644 --- a/src/cattrs/converters.py +++ b/src/cattrs/converters.py @@ -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 @@ -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 diff --git a/tests/test_converter.py b/tests/test_converter.py index ab86d55e..cc57b0e6 100644 --- a/tests/test_converter.py +++ b/tests/test_converter.py @@ -5,6 +5,7 @@ Annotated, Any, Deque, + ForwardRef, FrozenSet, List, MutableSequence, @@ -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."""