Skip to content

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

Description

@nmoreaud

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions