konradhalas / dacite

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

Add support for python enum.Enum #28

Closed maroshmka closed 5 years ago

maroshmka commented 5 years ago

Do not raise WrongTypeError when value is of type Enum. E.g. it can be Enum of ints, so first try to convert the value of int to Enum type.

For further details see tests.

konradhalas commented 5 years ago

Hi @maroshmka, thank you for your PR :)

In this case you should use cast parameter:

class MyEnum(enum.Enum):
    a: int = 1
    b: int = 3

@dataclass
class X:
    e: MyEnum = MyEnum.a

x = X()

result = from_dict(X, {"e": 1}, Config(cast=["e"]))

assert result == x
maroshmka commented 5 years ago

thanks, i'll try to use it.

It's just not very scalable tho. When you have bunch of dataclasses in your project and you add a Enum to random one, you need to add cast to every usage of from_dict with that class :/

And what if I have enum inside inner dataclass? Can cast do it?

@dataclass
class X:
    e: MyEnum = MyEnum.a

@dataclass
class Y:
    x: X

y = Y()

# can I do something like this ???
result = from_dict(Y, {"x": {"e": 1}}, Config(cast=["x.e"]))

assert result == x

If not I may implement that :)

konradhalas commented 5 years ago

Agree, this is why I'm thinking about two possible solutions:

maroshmka commented 5 years ago

That seems like a bigger issue. But I think theres a difference - mostly when you want some special deserialization, it is because of your own created type. Enum is not own type, its python (not primitive tho).

btw: cast=["x.e"] dot notation works (if someone would be asking), maybe it would be nice to add it to doc?

Thank you for discussion 🙂