Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3.9+ style collections with forward references fails to resolve types #256

Open
mwoods-familiaris opened this issue May 29, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@mwoods-familiaris
Copy link

mwoods-familiaris commented May 29, 2024

Describe the bug
Collections and forward references seem to work in isolation, or when used together providing the typing.List style collection type annotation is used. When using python 3.9 style collections, dacite fails to resolve type mapping.

To Reproduce
Taking the example from the docs and amending it to use a python 3.9 style list type annotation, with a forward reference to "A":

@dataclass
class A:
    x: str
    y: int

@dataclass
class B:
    a_list: list["A"]


data = {
    'a_list': [
        {
            'x': 'test1',
            'y': 1,
        },
        {
            'x': 'test2',
            'y': 2,
        }
    ],
}

result = from_dict(data_class=B, data=data)

assert result == B(a_list=[A(x='test1', y=1), A(x='test2', y=2)])

results in:

dacite.exceptions.WrongTypeError: wrong value type for field "a_list" - should be "list" instead of value "[{'x': 'test1', 'y': 1}, {'x': 'test2', 'y': 2}]" of type "list"

Expected behavior
To successfully resolve list["A"], in the same manner as with the following alternatives (e.g. all these other combinations of annotations work as expected, where typing.List is used, or forward references are avoided):

typing.List with no forward reference:

@dataclass
class B:
    a_list: List[A]

typing.List with forward reference:

@dataclass
class B:
    a_list: List["A"]

python 3.9+ list with no forward reference:

@dataclass
class B:
    a_list: list[A]

Environment

  • Python version: 3.9.13
  • dacite version: 1.8.1

Additional context
Explicitly passing in the forward references with config=Config(forward_references={"A": A}) has no impact.

@mwoods-familiaris mwoods-familiaris added the bug Something isn't working label May 29, 2024
@mwoods-familiaris
Copy link
Author

Just to add...possibly relates to this:

Note
PEP 585 generic types such as list["SomeClass"] will not be implicitly transformed into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass].

Ref: https://docs.python.org/3.9/library/typing.html#typing.ForwardRef

@marcelolima
Copy link

facing same issue, any updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants