PEP 837: Extensible JSON serialization

I’d actually strongly recommend not adding __json__ to dataclasses this way. dataclasses.asdict does a lot of extra work that isn’t needed for __json__ and is slow. It recurses into other objects and makes deep copies of every unknown thing it encounters which is completely unnecessary if the goal is to subsequently convert everything to a JSON string.

For __json__ it would make more sense to create a (lazily) generated method that doesn’t recurse itself. It could then also write out the dict explicitly rather than needing to loop through fields at runtime which would make serialization significantly faster.

2 Likes