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

Is it possible to serialize a class without instanciating a dict? (ie: use a generator) #315

Open
nmoreaud opened this issue Aug 11, 2023 · 1 comment

Comments

@nmoreaud
Copy link

Hello,
I wonder if it is possible, to serialize a class to a dict using a generator.
It could help to reduce memory allocations when serializing dataclasses with __slots__.

I think about something like this:

from dataclasses import dataclass
import json


@dataclass
class Data:
    __slots__ = ('a', 'b')

    a: int
    b: int

    def items(self):
        yield ('a', self.a)
        yield ('b', self.b)


def default(obj):
    if isinstance(obj, Data):
        return obj.items()  # ko
        # return dict(obj.items()) # OK
        # return {'toto': 'tata'}.items()  # ko


data = {"data": Data(a=1, b=2)}
j = json.dumps(data, default=default)
print(j)
@nmoreaud nmoreaud changed the title Is it possible to serialize a class without instanciating a dict (ie: use a generator) Is it possible to serialize a class without instanciating a dict? (ie: use a generator) Aug 11, 2023
@etrepum
Copy link
Member

etrepum commented Aug 11, 2023

No, that is not currently possible. isinstance(obj, dict) must be True in order for it to serialize as a JSON object. I think it's unlikely to make all that much of a difference, but you're welcome to try it. If you can show it does improve performance in a meaningful way and provide a PR with tests then I'd be happy to review it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants