Skip to content

Commit 30fb43e

Browse files
authored
Fix type resolution (#662)
* Add test for type resolution using generics and forward references * Fix type resolution call * Add assert statement * Avoid unnecessary import * Adjust docstring * Update changelog * Rename test * Add structuring operation to test * Add full stop to changelog * Rename forwardrefs.py to generics.py * Put everything under test_generics_649.py
1 parent 0c226c2 commit 30fb43e

3 files changed

Lines changed: 28 additions & 1 deletion

File tree

HISTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ Our backwards-compatibility policy can be found [here](https://github.com/python
1919
and {func}`cattrs.gen.typeddicts.make_dict_structure_fn` will use the value for the `use_alias` parameter from the given converter by default now.
2020
If you're using these functions directly, the old behavior can be restored by passing in the desired value directly.
2121
([#596](https://github.com/python-attrs/cattrs/issues/596) [#660](https://github.com/python-attrs/cattrs/pull/660))
22+
- Fix unstructuring of generic classes with stringified annotations.
23+
([#661](https://github.com/python-attrs/cattrs/issues/661) [#662](https://github.com/python-attrs/cattrs/issues/662))
2224

2325
## 25.1.1 (2025-06-04)
2426

src/cattrs/converters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1252,7 +1252,7 @@ def gen_unstructure_attrs_fromdict(
12521252
attribs = fields(origin or cl)
12531253
if attrs_has(cl) and any(isinstance(a.type, str) for a in attribs):
12541254
# PEP 563 annotations - need to be resolved.
1255-
resolve_types(cl)
1255+
resolve_types(origin or cl)
12561256
attrib_overrides = {
12571257
a.name: self.type_overrides[a.type]
12581258
for a in attribs

tests/test_generics_649.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""Tests for PEP 649 (Deferred Evaluation Of Annotations Using Descriptors)."""
2+
3+
from __future__ import annotations
4+
5+
from typing import Generic, TypeVar
6+
7+
from attrs import define
8+
9+
from cattrs import Converter
10+
11+
T = TypeVar("T")
12+
13+
14+
@define
15+
class GenericClass(Generic[T]):
16+
t: T
17+
18+
19+
def test_generics_with_stringified_annotations():
20+
"""Type resolution works with stringified annotations."""
21+
converter = Converter()
22+
inst = GenericClass(42)
23+
dct = converter.unstructure(inst, unstructure_as=GenericClass[int])
24+
assert dct == {"t": 42}
25+
assert converter.structure(dct, GenericClass[int])

0 commit comments

Comments
 (0)