dacite icon indicating copy to clipboard operation
dacite copied to clipboard

Coerce `None` values to default values.

Open elpescado opened this issue 2 years ago • 0 comments

Consider:

from dataclasses import dataclass

@dataclass
class Widget:
    val: str = "test"

x = from_dict(data_class=Widget, data={}). # No `val` at all, default value is used
print(x)
y = from_dict(data_class=Widget, data={"val": None})
print(y)
Widget(val='test')
Traceback (most recent call last):
  File "dac.py", line 10, in <module>
    y = from_dict(data_class=Widget, data={"val": None})
  File "/lib/python3.9/site-packages/dacite/core.py", line 68, in from_dict
    raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
dacite.exceptions.WrongTypeError: wrong value type for field "val" - should be "str" instead of value "None" of type "NoneType"

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 of None. Currently the workaround is to use __post_init__ method of a dataclass:

@dataclass
class Widget:
    val: Optional[str] = "test"

    def __post_init__(self):
        if self.val is None:
            self.val = "test"

Which is, IMO, not elegant, requires field to be declared as Optional and requires repeated default value declarations.

elpescado avatar Jun 28 '22 11:06 elpescado