From 06cd7bd2de15b99febbacdd1482cda5374aca61c Mon Sep 17 00:00:00 2001 From: hemtilva Date: Mon, 16 Nov 2026 03:49:17 +0530 Subject: [PATCH] Apply type arguments when unstructuring generic type aliases Generic PEP 695 type aliases like `type Pair[T] = tuple[T, T]` were unstructured using the hook for their unparametrized base, so the type arguments were dropped and nested attrs classes, dataclasses and other values were left unconverted. Structuring already substituted the type arguments; unstructuring now does the same. --- HISTORY.md | 1 + src/cattrs/converters.py | 8 ++------ src/cattrs/typealiases.py | 27 ++++++++++++++++++++++++--- tests/test_generics_695.py | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 9 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 942616e3..8c6e590f 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -13,6 +13,7 @@ Our backwards-compatibility policy can be found [here](https://github.com/python ## NEXT +- Fix generic [PEP 695](https://peps.python.org/pep-0695/) type aliases (like `type Pair[T] = tuple[T, T]`) being unstructured without their type arguments, which left nested _attrs_ classes, dataclasses and values like datetimes unconverted (for example, `Pair[SomeClass]`). The type arguments are now applied before looking up the unstructure hook, matching what structuring already did. - 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..ed1bbe6b 100644 --- a/src/cattrs/converters.py +++ b/src/cattrs/converters.py @@ -115,9 +115,9 @@ sentinel_unstructure, ) from .typealiases import ( - get_type_alias_base, is_type_alias, type_alias_structure_factory, + type_alias_unstructure_factory, ) from .types import SimpleStructureHook @@ -261,11 +261,7 @@ def __init__( lambda t: self.get_unstructure_hook(get_final_base(t)), True, ), - ( - is_type_alias, - lambda t: self.get_unstructure_hook(get_type_alias_base(t)), - True, - ), + (is_type_alias, type_alias_unstructure_factory, "extended"), (is_mapping, self._unstructure_mapping), (is_sequence, self._unstructure_seq), (is_mutable_set, self._unstructure_seq), diff --git a/src/cattrs/typealiases.py b/src/cattrs/typealiases.py index d3a20c48..4131dd4a 100644 --- a/src/cattrs/typealiases.py +++ b/src/cattrs/typealiases.py @@ -7,13 +7,18 @@ from ._compat import is_generic from ._generics import deep_copy_with -from .dispatch import StructureHook +from .dispatch import StructureHook, UnstructureHook from .gen._generics import generate_mapping if TYPE_CHECKING: from .converters import BaseConverter -__all__ = ["get_type_alias_base", "is_type_alias", "type_alias_structure_factory"] +__all__ = [ + "get_type_alias_base", + "is_type_alias", + "type_alias_structure_factory", + "type_alias_unstructure_factory", +] if sys.version_info >= (3, 12): from types import GenericAlias @@ -41,7 +46,8 @@ def get_type_alias_base(type: Any) -> Any: return type.__value__ -def type_alias_structure_factory(type: Any, converter: BaseConverter) -> StructureHook: +def _get_parametrized_base(type: Any) -> Any: + """Get the base of a type alias, with type parameters applied.""" base = get_type_alias_base(type) if is_generic(type): mapping = generate_mapping(type) @@ -50,8 +56,23 @@ def type_alias_structure_factory(type: Any, converter: BaseConverter) -> Structu base = mapping[base.__name__] else: base = deep_copy_with(base, mapping) + return base + + +def type_alias_structure_factory(type: Any, converter: BaseConverter) -> StructureHook: + base = _get_parametrized_base(type) res = converter.get_structure_hook(base) if res == converter._structure_call: # we need to replace the type arg of `structure_call` return lambda v, _, __base=base: __base(v) return lambda v, _, __base=base: res(v, __base) + + +def type_alias_unstructure_factory( + type: Any, converter: BaseConverter +) -> UnstructureHook: + """Unstructure a type alias using the hook of its base. + + Type parameters of generic type aliases are applied to the base first. + """ + return converter.get_unstructure_hook(_get_parametrized_base(type)) diff --git a/tests/test_generics_695.py b/tests/test_generics_695.py index 56385013..82cbe28b 100644 --- a/tests/test_generics_695.py +++ b/tests/test_generics_695.py @@ -116,3 +116,36 @@ def test_generic_type_alias(converter: BaseConverter): type Gen2[K, V] = dict[K, V] assert converter.structure({"a": "1"}, Gen2[str, int]) == {"a": 1} + + +def test_generic_type_alias_unstructure(converter: BaseConverter): + """Generic type aliases are unstructured using their type arguments.""" + + @define + class A: + a: int + + type Gen1[T] = T + type Gen2[K, V] = dict[K, V] + + assert converter.unstructure(A(1), Gen1[A]) == {"a": 1} + assert converter.unstructure({"a": A(1)}, Gen2[str, A]) == {"a": {"a": 1}} + + if isinstance(converter, Converter): + # Heterogeneous tuples are only supported on a Converter + type Pair[T] = tuple[T, T] + + assert converter.unstructure((A(1), A(2)), Pair[A]) == ({"a": 1}, {"a": 2}) + + @define + class B: + pair: Pair[A] + mapping: Gen2[str, A] + + b = B((A(1), A(2)), {"a": A(3)}) + unstructured = converter.unstructure(b) + assert unstructured == { + "pair": ({"a": 1}, {"a": 2}), + "mapping": {"a": {"a": 3}}, + } + assert converter.structure(unstructured, B) == b