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
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
8 changes: 2 additions & 6 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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),
Expand Down
27 changes: 24 additions & 3 deletions src/cattrs/typealiases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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))
33 changes: 33 additions & 0 deletions tests/test_generics_695.py
Original file line number Diff line number Diff line change
Expand Up @@ -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