Closed maroshmka closed 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
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 :)
Agree, this is why I'm thinking about two possible solutions:
cast_all
parameter,cast
at all - there are more mature libs (like DRF or Marshmallow) which are focused on data validation/serialization. dacite
should be used in conjunction with such lib and this lib should generate proper values (enums in your case) which user should pass to dacite
to build data class.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).
cast_all
, to try to deserialize all the attributes as they were defined in dataclass 👍 serializer
arg, which can be drf.Serializer
type to use for deserialization -> imho this is not needed, at least now.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 🙂
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.