konradhalas / dacite

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

support non-default value field missing in dict #198

Closed thincal closed 1 year ago

thincal commented 1 year ago

If incoming dict misses some fields, the dacite.from_dict would raise the MissingValueError exception.

To let it work, either the dict must be carrying with complete fields or the dataclass be declared with default value, either way requires a bit of work.

For example:

import dacite
import dataclasses

@dataclasses.dataclass
class Example:
    a: int
    b: str

assert Example(a=1, b=None) == dacite.from_dict(Example, {"a": 1})

# Exception:

Exception has occurred: MissingValueError
missing value for field "b"

Proposal solution:

adding a allow_missing_fields_as_none option into Config, such as:

dacite.from_dict(Example, {"a": 1}, config=Config{allow_missing_fields_as_none=True})
konradhalas commented 1 year ago

@thincal thank you for reporting this issue, but TBH I don't like this approach. If b can be None you should reflect this in your types.

Working example:

import dataclasses
from typing import Optional

import dacite

@dataclasses.dataclass
class Example:
    a: int
    b: Optional[str]

assert Example(a=1, b=None) == dacite.from_dict(Example, {"a": 1})