konradhalas / dacite

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

Enums inside frozenset didn't casted well #187

Closed artemmyhda closed 1 year ago

artemmyhda commented 2 years ago

If we have a dataclass like this:

class A(Enum):
    a = 'a'
    b = 'b'

@dataclass
class B:
    a: FrozenSet[A]

from_dict() will not cast values inside this frozenset:

from_dict(data_class=B, data={'a': ['a', 'b']}, config=Config(cast=[frozenset]))

>>> raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
>>> dacite.exceptions.WrongTypeError: wrong value type for field "a" - should be "typing.FrozenSet[A]" 
>>> instead of value "frozenset({'a', 'b'})" of type "frozenset"

It entails the necessity of writing custom type hooks for each frozenset in our dataclass like this:

def _frozenset_of_A_type_hook(value):
    return frozenset({A(item) for item in value})

from_dict(
    data_class=B, 
    data={'a': ['a', 'b']}, 
    config=Config(
        cast=[frozenset], 
        type_hooks={FrozenSet[A]: _frozenset_of_A_type_hook}
    )
)
konradhalas commented 1 year ago

@artemmigda thank you for reporting this issue.

I think you can solve your problem witch such configuration:

Config(cast=[A], type_hooks={FrozenSet[A]: frozenset})