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

Nested dataclass in Optional not instantiated #10

Open
ROpdebee opened this issue Jun 11, 2019 · 0 comments
Open

Nested dataclass in Optional not instantiated #10

ROpdebee opened this issue Jun 11, 2019 · 0 comments

Comments

@ROpdebee
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant