Open davetapley opened 9 months ago
I'd hoped to work around it with this ⬇️ but it doesn't work (same error) 😞
class Serializer:
@dispatch
def serialize(self, value: MyEnum) -> Any:
return value.value
class Deserializer:
@dispatch
def deserialize(self, cls: Type[MyEnum], value: Any) -> MyEnum:
return MyEnum(value)
serde.add_serializer(Serializer())
serde.add_deserializer(Deserializer())
I wondered if wrapping in a class might help, but no luck:
class MyDict(dict[MyEnum, str]):
...
class Serializer:
@dispatch
def serialize(self, value: MyDict) -> dict[str, str]:
return {k.value: v for k, v in value.items()}
class Deserializer:
@dispatch
def deserialize(self, cls: Type[MyDict], value: dict[str, str]) -> MyDict:
return MyDict({MyEnum(k): v for k, v in value.items()})
Ah, if I wrap it in a class (instead of inheriting) then it works out of the box (i.e. no serializer needed):
@dataclass
class MyClass:
my_dict: dict[MyEnum, str]
my_class = MyClass({
MyEnum.FOO: 'foo',
MyEnum.BAR: 'bar',
})
json = to_json(my_class)
print(json)
my_class_ = from_json(MyClass, json)
print(my_class_)
{"my_dict":{"foo":"foo","bar":"bar"}}
MyClass(my_dict={<MyEnum.FOO: 'foo'>: 'foo', <MyEnum.BAR: 'bar'>: 'bar'})
That'll do as a workaround for now! ✅
It would be nice if this worked:
But currently (
0.13.0
) is: