Closed dddvision closed 1 year ago
It does :)
Here's how:
MyEnum
just from Enum
, the StackOverflow answer I found too is misleading. Enum
as part of the Config
Config
class for it to work, it's not directly visible in the documentation and I missed it at first too. This sample is your fixed code:
import dataclasses
from enum import Enum
from dacite import from_dict, Config
class MyEnum(Enum): INVALID = "INVALID" FOO = "FOO" BAR = "BAR"
@dataclasses.dataclass class MyDataClass: my_enum: MyEnum = MyEnum.INVALID
invalidclass = MyDataClass(my_enum=MyEnum.INVALID)
x = from_dict(MyDataClass, {"my_enum": "INVALID"}, config=Config(cast=[Enum])) # cast it here
assert x == invalidclass # passes
@bytinbit thank you for the good answer :)
Is there a way to automate this?
In this case MyDataClass knows exactly which Enum it expects, why doesn't it just try this cast automatically?
It's a little cumbersome to have a list of 12 enums in the Config for every call to from_dict.
Thanks for producing this tool. Unfortunately, it currently does not seem to handle string enum fields.
Exception has occurred: WrongTypeError (note: full exception trace is shown but execution is paused at: _run_module_as_main) wrong value type for field "my_enum" - should be "MyEnum" instead of value "INVALID" of type "str" File "/home/diel.david@aurora.aero/anaconda3/lib/python3.9/site-packages/dacite/core.py", line 68, in from_dict raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)