konradhalas / dacite

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

Undesirable WrongTypeError in from_dict() when input dict field has explicit None value #69

Closed navndn closed 4 years ago

navndn commented 4 years ago

I have a use-case similar to below code ...

from dacite import from_dict
from dataclasses import dataclass, asdict

@dataclass
class A():
    x: str = None

# a1 = A('a1')
a1 = A()
a2 = from_dict(A, asdict(a1))

Error:

WrongTypeError: wrong type for field "x" - should be "str" instead of "NoneType"

Is this expected behaviour? Is there a work-around other than using custom asdict function which skips None valued keys?

Thanks!

konradhalas commented 4 years ago

@navndn thank you for reporting this issue :)

It looks that your initial typings are wrong, field x is not str, it's Optional[str].

Please try:

from typing import Optional

@dataclass
class A():
    x: Optional[str] = None