Closed nmhub closed 2 years ago
Try that:
from dataclasses import dataclass, field
from typing import Optional
from dacite import from_dict
@dataclass
class Bar:
a_key: Optional[str] = None
@dataclass
class Foo:
test: str
bar: Bar = field(default_factory=lambda: Bar())
test_data = {"test": "lorem"}
print(from_dict(data_class=Foo, data=test_data))
test_data_2 = {"test": "lorem", "bar": {}}
print(from_dict(data_class=Foo, data=test_data_2))
test_data_3 = {"test": "lorem", "bar": {"a_key": "test1"}}
print(from_dict(data_class=Foo, data=test_data_3))
for bar set field with default_factory creating Bar object if data missing in process of creation Foo object.
Thank you for sharing that. It works perfectly! I learned something new too.
Is there any way to have optional keys in a nested dict? The following results in MissingValueError:
I'm trying to end up with
a_key = None.
I've tried withOptional[Bar]
, but that just showsNone
and loses the key names inBar
Thanks very much for this awesome library!