Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom class serializer doesn't work for nested data? #261

Open
AustinScola opened this issue Aug 30, 2022 · 1 comment
Open

Custom class serializer doesn't work for nested data? #261

AustinScola opened this issue Aug 30, 2022 · 1 comment

Comments

@AustinScola
Copy link

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 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

from dataclasses import dataclass
from datetime import datetime
from typing import Any

from serde import SerdeSkip, serde
from serde.json import to_json


def serializer(cls, o):
    if cls is datetime or isinstance(o, datetime):
        return o.timestamp()
    else:
        raise SerdeSkip()


@serde(serializer=serializer)
@dataclass
class Foo:
    bar: dict[str, Any]


def main():
    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()
@yukinarit
Copy link
Owner

Hi @AustinScola

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)
@dataclass
class Foo:
    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.

@yukinarit yukinarit added this to 📝 Backlog in Roadmap via automation Sep 3, 2022
@yukinarit yukinarit removed this from 📝 Backlog in Roadmap Jun 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

2 participants