Repository navigation
Description
When a generic PEP 695 type alias such as type Pair[T] = tuple[T, T] is used with concrete type arguments, unstructure ignores those arguments. The unstructure hook is looked up for the alias's raw value (tuple[T, T], with the type variable still in it) instead of tuple[Point, Point]. Nested attrs classes, dataclasses and things like datetimes come back unchanged, so the output is not primitive data, and the JSON converter fails to dump it.
Structuring the same types already works, because type_alias_structure_factory substitutes the type arguments before it looks up the hook (that was added for structuring in #618). The unstructure side in BaseConverter.__init__ still calls get_type_alias_base(t), which just returns t.__value__. On a subscripted alias that attribute is forwarded to the unsubscripted alias.
Reproducer (cattrs 26.2.1 on Python 3.12, and current main on Python 3.15):
from datetime import datetime
from attrs import define
from cattrs import Converter
from cattrs.preconf.json import make_converter
type Pair[T] = tuple[T, T]
type Registry[K, V] = dict[K, V]
@define
class Point:
x: int
@define
class Shape:
corners: Pair[Point]
stamps: Registry[str, datetime]
c = Converter()
shape = Shape((Point(1), Point(2)), {"a": datetime(2020, 1, 1)})
print(c.unstructure(shape))
print(c.unstructure((Point(1), Point(2)), Pair[Point]))
print(make_converter().dumps(shape))Actual output:
{'corners': (Point(x=1), Point(x=2)), 'stamps': {'a': datetime.datetime(2020, 1, 1, 0, 0)}}
(Point(x=1), Point(x=2))
TypeError: Object of type Point is not JSON serializable
Expected output:
{'corners': ({'x': 1}, {'x': 2}), 'stamps': {'a': datetime.datetime(2020, 1, 1, 0, 0)}}
({'x': 1}, {'x': 2})
{"corners": [{"x": 1}, {"x": 2}], "stamps": {"a": "2020-01-01T00:00:00"}}
Aliases like type L[T] = list[T] happen to work because the list hook falls back to dispatching on each element's runtime class. Heterogeneous tuples, dicts and type Gen[T] = T do not get that fallback. Their type variable resolves to a passthrough hook, so the data is silently left unconverted. A plain tuple[Point, Point] annotation, or a non-generic alias, works fine.
I have a small fix with a test in tests/test_generics_695.py and will open a PR.
Activity