Skip to content
2 changes: 1 addition & 1 deletion src/cattrs/converters.py
Comment thread
AdrianSosic marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,7 @@ def gen_unstructure_attrs_fromdict(
attribs = fields(origin or cl)
if attrs_has(cl) and any(isinstance(a.type, str) for a in attribs):
# PEP 563 annotations - need to be resolved.
resolve_types(cl)
resolve_types(origin or cl)
attrib_overrides = {
a.name: self.type_overrides[a.type]
for a in attribs
Expand Down
14 changes: 14 additions & 0 deletions tests/forwardrefs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Class definitions using forward references."""

from __future__ import annotations

from typing import Generic, TypeVar

from attrs import define

T = TypeVar("T")


@define
class GenericClass(Generic[T]):
t: T
8 changes: 8 additions & 0 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import pytest
from attrs import asdict, define

import cattrs
Comment thread
AdrianSosic marked this conversation as resolved.
Outdated
from cattrs import BaseConverter, Converter
from cattrs._compat import Protocol
from cattrs._generics import deep_copy_with
from cattrs.errors import StructureHandlerNotFoundError
from cattrs.gen._generics import generate_mapping

from ._compat import Dict_origin, List_origin, is_py310_plus, is_py311_plus
from .forwardrefs import GenericClass

T = TypeVar("T")
T2 = TypeVar("T2")
Expand Down Expand Up @@ -358,3 +360,9 @@ class GenericEntity(GenericProtocol[int]):
assert generate_mapping(GenericEntity) == {"T": int}

assert converter.structure({"a": 1}, GenericEntity) == GenericEntity(1)


def test_generics_with_forward_refs():
Comment thread
AdrianSosic marked this conversation as resolved.
Outdated
Comment thread
AdrianSosic marked this conversation as resolved.
Outdated
"""Type resolution works with forward references."""
converter = cattrs.Converter()
converter.unstructure(GenericClass(42), unstructure_as=GenericClass[int])
Comment thread
AdrianSosic marked this conversation as resolved.
Outdated
Loading