dataclasses-json
dataclasses-json copied to clipboard
Parsing Bug - typing.List of Dataclass with an Enum
This one is really strange and I could not troubleshoot it easily
- xs hides value and the generator can be called only once, so it's hard to troubleshoot
I can't provide the exact details but we have a parsing error (tried both from_dict and from_json).
Exact Error: Type List cannot be instantiated; use list() instead
This started when I added an enum inside a dataclass that is in a typing.List of another dataclass.
The datacclass format looks like this:
@dataclass_json @dataclass class Message:
my_list: typing.List[ListClass]
@dataclass_json @dataclass class ListClass:
enum_value: MyEnum
We work around it with the following code:
A bug in dataclasses-json confuses the parsing.
enum_value: str = field(
metadata=config(
encoder=_get_enum_value,
decoder=_get_enum_value_str))
I had the same problem. Adding str
mix-in to the enum class as described in the official Python docs helped, ie.:
class MyEnum(str, Enum):
...
I tried to repreduce this with the following code in the newest master version, but it ran just fine:
class MyEnum(enum.Enum):
STR = "str"
FLOAT = 1.0
@dataclass_json
@dataclass
class ListClass:
enum_value: MyEnum
@dataclass_json
@dataclass
class Message:
my_list: typing.List[ListClass]
Message.from_json('{"my_list":[{"enum_value":"str"}]}')
Message(my_list=[ListClass(enum_value=<MyEnum.STR: 'str'>)])
If you still face issues, please repoen with more details, e.g. Python version and dataclasses-json version.