|
|
|
|
|
by glyph
3585 days ago
|
|
None of this is a problem with attrs. Serialize however you like. >>> import attr
>>>
>>> @attr.s
... class Thing(object):
... a = attr.ib()
... b = attr.ib()
...
...
>>> @attr.s
... class Many(object):
... things = attr.ib()
...
...
>>> many = Many([Thing(1, 2), Thing(3, 4)])
>>> many
Many(things=[Thing(a=1, b=2), Thing(a=3, b=4)])
>>> attr.asdict(many)
{'things': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]}
>>> import pickle
>>> pickle.dumps(many)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nMany\np1\nc__builtin__\nobject\np2\n
Ntp3\nRp4\n(dp5\nS'things'\np6\n(lp7\ng0\n(c__main__\nThing\np8\ng2\nNtp9\nRp10\
n(dp11\nS'a'\np12\nI1\nsS'b'\np13\nI2\nsbag0\n(g8\ng2\nNtp14\nRp15\n(dp16\ng12\n
I3\nsg13\nI4\nsbasb."
>>> import json
>>> json.dumps(attr.asdict(many))
'{"things": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}'
>>>
|
|
You call attr.asdict() and it searches the attribute values, including inside lists, for more attr objects to convert into dict values?
What kinds of values does it search through? The documentation doesn't say, it just gives an example where it works inside a list for some reason.