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
I'm running into an issue with a custom class level serializer. I have a dataclass with a field that is a dictionary and I want all datetimes in the dict to be serialized using .timestamp(). This seems to work for top level values, but not for anything nested ? I'm not sure exactly what the expected behavior is here? Is there a different way to accomplish this or is it a bug?
Example
fromdataclassesimportdataclassfromdatetimeimportdatetimefromtypingimportAnyfromserdeimportSerdeSkip, serdefromserde.jsonimportto_jsondefserializer(cls, o):
ifclsisdatetimeorisinstance(o, datetime):
returno.timestamp()
else:
raiseSerdeSkip()
@serde(serializer=serializer)@dataclassclassFoo:
bar: dict[str, Any]
defmain():
d=datetime(2021, 1, 1, 0, 0, 0)
foo=Foo(bar={"d": d})
print(to_json(foo)) # prints {"bar":{"d":1609477200.0}}# The nested datetime here isn't serialized as I would expect it to be?d=datetime(2021, 1, 1, 0, 0, 0)
foo=Foo(bar={"a": {"d": d}})
print(to_json(foo)) # prints {"bar":{"a":{"d":"2021-01-01T00:00:00"}}}if__name__=='__main__':
main()
The text was updated successfully, but these errors were encountered:
pyserde doesn't inspect the nested type at Runtime if the type is declared as Any. That is because of the performance.
The library like dataclasses-json does runtime type inspection therefore it was said to be really slow.
I wanted to provide this code as a workaround
@serde(serializer=serializer)@dataclassclassFoo:
bar: dict[str, Union[datetime, dict[str, datetime]]]
But it seems custom serializer isn't supported for Union yet 😄
Let me check if I can quickly implement it.
Hey @yukinarit,
I'm running into an issue with a custom class level serializer. I have a
dataclass
with a field that is a dictionary and I want alldatetime
s in the dict to be serialized using.timestamp()
. This seems to work for top level values, but not for anything nested ? I'm not sure exactly what the expected behavior is here? Is there a different way to accomplish this or is it a bug?Example
The text was updated successfully, but these errors were encountered: