Open tzah4748 opened 11 months ago
Update:
The problem originates from dacite/dataclasses.py
def create_instance(data_class: Type[T], init_values: Data, post_init_values: Data) -> T:
instance = data_class(**init_values)
for key, value in post_init_values.items():
setattr(instance, key, value)
return instance
Why would you need the post_init_values
and why would you need to set these attributes ?
If a field is init=True
it's value will be assigned in instance creation explicitly or by the defined field's default/default_factory
If a field is init=False
it is expected to:
default
/default_factory
assigned.__post_init__
method.In all possible cases, you shouldn't override the value using that for loop on the _post_init_values.items()
For the very least, if this is really needed for some reason (unknown to me), you could easily fix this by adding a call to the instance's __post_init__
method, if defined.
def create_instance(data_class: Type[T], init_values: Data, post_init_values: Data) -> T:
instance = data_class(**init_values)
for key, value in post_init_values.items():
setattr(instance, key, value)
if hasattr(instance, "__post_init__"):
instance.__post_init__()
return instance
Describe the bug When one of the dataclass's fields is a
field(init=False, default_factory=list/dict/whatever)
Usingfrom_dict
to load an instance of the dataclass results in the field being overridden to thedefault_factory
value effectively ignoring any modifications done in the__post_init__
method of the class.To Reproduce
Expected behavior
Environment
dacite
version: 1.8.1