You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It seems that custom serializers don't work if the custom data type is at the top level.
For example, suppose I implement a custom serializer for MyClass, and I wrap MyClass inside a dataclass MyWrapper.
When I call serde.to_dict(MyWrapper(MyClass(...))), the custom serializer for MyClass works as expected.
When I call serde.to_dict(MyClass(...)), however, the custom serializer is not used.
This is unexpected; I would expect serde.to_dict(MyClass(...)) to invoke the custom serializer too.
In the below example, the second assertion fails.
# serde_partial.pyfromplumimportdispatchimportserdefromtypingimportAnyfromdataclassesimportdataclassType=type# You should prefer to use type[...] instead of Type[...]!classMyClass:
def__init__(self, a, b):
self.a=aself.b=bdef__eq__(self, other):
returnself.a==other.aandself.b==other.bclassMySerializer:
@dispatchdefserialize(self, value: MyClass) ->dict[str, Any]:
return {'a': value.a, 'b': value.b}
classMyDeserializer:
@dispatchdefdeserialize(self, cls: Type[MyClass], value: dict[str, Any]) ->MyClass:
returnMyClass(value['a'], value['b'])
serde.add_serializer(MySerializer())
serde.add_deserializer(MyDeserializer())
@dataclassclassMyWrapper:
value: MyClass# When MyClass is wrapped inside a dataclass, to_dict and from_dict work correctlyobj=MyWrapper(MyClass(1, 2))
expected= {'value': {'a': 1, 'b': 2}}
result=serde.to_dict(obj)
assertisinstance(result, dict)
assertresult==expectedassertserde.from_dict(MyWrapper, result) ==obj# When MyClass is not wrapped inside a dataclass, to_dict fails to serialize itobj=MyClass(1, 2)
expected= {'a': 1, 'b': 2}
result=serde.to_dict(obj)
assertisinstance(result, dict), f"Expected dict, got {type(result)}"# ASSERTION FAILS
It seems that custom serializers don't work if the custom data type is at the top level.
For example, suppose I implement a custom serializer for
MyClass
, and I wrapMyClass
inside a dataclassMyWrapper
.When I call
serde.to_dict(MyWrapper(MyClass(...)))
, the custom serializer forMyClass
works as expected.When I call
serde.to_dict(MyClass(...))
, however, the custom serializer is not used.This is unexpected; I would expect
serde.to_dict(MyClass(...))
to invoke the custom serializer too.In the below example, the second assertion fails.
The text was updated successfully, but these errors were encountered: