konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 106 forks source link

Optional with default None gives a TypeError for python3.9 with modern annotation syntax #213

Closed gaatjeniksaan closed 1 year ago

gaatjeniksaan commented 1 year ago

Describe the bug When defining a class with modern type annotation syntax, dacite.from_dict fails behind the scenes when get_type_hints is called.

To Reproduce

from __future__ import annotations
from dataclasses import dataclass
from dacite import from_dict

@dataclass
class Foo:
    bar: str
    baz: str | None = None

data = {"bar": "OptimusPrime"}
from_dict(Foo, data)

Results in:

TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'

Environment

Additional context I've tried with python 3.10, and that works as normal. If I replace the Foo class with `Optional[str] syntax it works. Is there any way of using modern type annotation syntax? The data class I'm casting to is not mine to change...

@dataclass
class Foo:
    bar: str
    baz: Optional[str] = None
gaatjeniksaan commented 1 year ago

Hmm my search was suboptimal, as this has been flagged before, but only for python 3.10 where the union type operator | is default behaviour. When importing the functionality through from __future__ import annotations in python3.9 it doesn't unfortunately.

gaatjeniksaan commented 1 year ago

Never mind, this is a typing.get_type_hints issue, not a dacite issue. Apologies for the noise.