konradhalas / dacite

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

Nested optional? #165

Closed nmhub closed 2 years ago

nmhub commented 2 years ago

Is there any way to have optional keys in a nested dict? The following results in MissingValueError:

@dataclass
class Bar:
       a_key: Optional[str]

@dataclass
class Foo:
       bar: Bar
       test: str

test_data = {"test":"lorem"}

from_dict(data_class:Foo, data=test_data)

I'm trying to end up with a_key = None. I've tried with Optional[Bar], but that just shows None and loses the key names in Bar

Thanks very much for this awesome library!

esentino commented 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.

nmhub commented 2 years ago

Thank you for sharing that. It works perfectly! I learned something new too.