konradhalas / dacite

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

Compatibility in from_dict for frozen dataclasses where dict doesn't contain non-init fields #195

Closed das-intensity closed 1 year ago

das-intensity commented 1 year ago

This issue is a subset of #181, where you can't initialize a dataclass with frozen fields. However the difference here is that we aim to fix this specifically for the case where the data dict does not contain the specific field.

from dacite import from_dict
from dataclasses import dataclass, field

@dataclass(frozen=True)
class X:
    y: str = field(init=False, default="value")

from_dict(data_class=X, data={}) # throws exception dataclasses.FrozenInstanceError: cannot assign to field 'y'

While appearing similar, this (sub)issue greatly simplifies the reasoning, and thus the fix is more clear. The reason is that if the field exists in the dict we're ingesting, there's a question as to how it should be applied/processed. Does it simply get injected after via ins.__dict__[k] = v or something? This issue intentionally does not require that question be answered.

konradhalas commented 1 year ago

@das-intensity thank you for reporting this issue.

This case is tricky but you are right, it should setup default value for this field. It's fixed via https://github.com/konradhalas/dacite/commit/667dfbae0df04a963f5b64db5cdd86ba38d9695e