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