Skip to content

Apply type arguments when unstructuring generic type aliases - #839

Open
hemtilva wants to merge 1 commit into
python-attrs:mainfrom
hemtilva:fix-generic-type-alias-unstructuring
Open

hemtilva wants to merge 1 commit into
python-attrs:mainfrom
hemtilva:fix-generic-type-alias-unstructuring

Conversation

@hemtilva

Copy link
Copy Markdown

Fixes #838.

Generic PEP 695 type aliases such as type Pair[T] = tuple[T, T] were unstructured with the hook for their raw value (tuple[T, T]), so their type arguments were dropped. Pair[SomeAttrsClass] or type Registry[K, V] = dict[K, V] with attrs class or datetime values came back with the instances unconverted. The JSON converter then failed to dump the result, and other converters produced non-primitive output. Structuring already substituted the type arguments in type_alias_structure_factory.

This change moves that substitution into a small helper in cattrs/typealiases.py and adds type_alias_unstructure_factory. The factory looks up the unstructure hook for the parametrized base. BaseConverter now registers that factory in place of the lambda that used get_type_alias_base directly. Non-generic aliases behave as before.

A test in tests/test_generics_695.py covers type Gen1[T] = T and type Gen2[K, V] = dict[K, V] on both converters. On Converter, which supports heterogeneous tuples, it also covers type Pair[T] = tuple[T, T] and an attrs class round trip. The test fails on main and passes with the change. I ran the full test suite on Python 3.12, with all extras, and on 3.15. On 3.15, the tests that need pyyaml or immutables could not be installed, so those were not run there. ruff check and ruff format are clean for the touched files. The one remaining ruff check finding (RUF063 in gen/typeddicts.py) was already on main.

HISTORY.md has an entry under NEXT.

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.
Copilot AI balanced review requested due to automatic review settings November 15, 2026 22:19

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Generic PEP 695 type aliases are unstructured without their type arguments

2 participants