typed-json-dataclass icon indicating copy to clipboard operation
typed-json-dataclass copied to clipboard

Nested dataclass in Optional not instantiated

Open ROpdebee opened this issue 5 years ago • 0 comments

Subject of the issue

Last one for tonight. See example and traceback.

Steps to reproduce

from typing import Optional
from dataclasses import dataclass
from typed_json_dataclass import TypedJsonMixin

@dataclass
class A(TypedJsonMixin):
    spam: str

@dataclass
class B(TypedJsonMixin):
    eggs: Optional[A]

B.from_json(B(A('foo')).to_json())

Expected behaviour

Result after from_json should be an instance B whose attribute eggs contains an instance A whose attribute spam contains 'foo'.

Actual behaviour

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    B.from_json(B(A('foo')).to_json())
  File "/Users/ruben/.local/share/virtualenvs/source-dQgmcX_Z/lib/python3.7/site-packages/typed_json_dataclass/typed_json_dataclass.py", line 232, in from_json
    return cls.from_dict(json.loads(raw_json), mapping_mode=mapping_mode)
  File "/Users/ruben/.local/share/virtualenvs/source-dQgmcX_Z/lib/python3.7/site-packages/typed_json_dataclass/typed_json_dataclass.py", line 216, in from_dict
    return cls(**raw_dict)
  File "<string>", line 3, in __init__
  File "/Users/ruben/.local/share/virtualenvs/source-dQgmcX_Z/lib/python3.7/site-packages/typed_json_dataclass/typed_json_dataclass.py", line 65, in __post_init__
    raise TypeError((f'{class_name}.{field_name} was '
TypeError: B.eggs was defined to be any of: (<class '__main__.A'>, <class 'NoneType'>) but was found to be <class 'dict'> instead

Optional[x] (i.e. Union[x, None]) where x is a dataclass should be instantiated from the dictionary if said dictionary is not None, similar to how it gets instantiated without the Optional type.

ROpdebee avatar Jun 11 '19 01:06 ROpdebee