I have two dataclasses, _Scrapped
and _Path
, where Scrapped contains a dict and a list where the values of the dict are Path objects and the items of the list are Path objects or None.
I’m using the following as a default
function to pass to json.dump(s):
def json_serializer(o: object) -> Any:
"""
To be passed as the `default` parameter to `json.dump` or `json.dumps`.
"""
print(type(o))
if dataclasses.is_dataclass(o) and not isinstance(o, type):
print(type(o))
return dataclasses.asdict(o)
... # other class hooks
raise TypeError(f"Cannot serialize {o!r}.")
When I pass a Scrapped object whose dict and list are empty to json.dumps, the scrapped type is printed twice, as it should.
When I pass a Path object directly to json.dumps, the path type is printed twice as well.
But when I pass _Scrapped({"a": _Path(...)})
to json.dumps, only the Scrapped type is printed (twice), the path class is not, because the function is not called on it, and for some even more mysterious reason the serialization goes through with no issue. How ?