Closed elpescado closed 1 year ago
Agree, I don't want a field to be optional, but I have a huge noSQL db to coerce into dataclass. Fields are optional in MongoDB of course, but if instead it is set to null, dacite crashes out.
@elpescado thank you for reporting this issue.
TBH I think that the current behaviour is correct: if field can have None
value, it should be Optional
. You can always remove all your fields with value None
before you pass data to from_dict
- dacite
will assign default values for such field.
Example:
from dataclasses import dataclass
from dacite import from_dict
@dataclass
class Widget:
val: str = "test"
data = {"val": None}
x = from_dict(data_class=Widget, data={k: v for k, v in data.items() if v is not None})
print(x) # Widget(val='test')
Consider:
When a field has a default value and is not declared as
Optional
, it could be useful to have (possibly an opt-in config option) to use default values instead ofNone
. Currently the workaround is to use__post_init__
method of adataclass
:Which is, IMO, not elegant, requires field to be declared as
Optional
and requires repeated default value declarations.