On Thu, Dec 10, 2020 at 12:38 AM sam bland <[email protected]> wrote:
>
> In response to the additional work required to convert the new python
> dataclass using the json encoder I propose an __encode__ method that will be
> included in the default dataclass attributes. This would then be picked up by
> the default json encoder and called to encode the object. Using a common
> __encode__ tag would allow the solution to also be applied to custom objects
> and other new objects without needing to update all json encoders. The
> __encode__ method would work similar to __repr__ but output a json string of
> the object.
>
There's actually a pretty easy way to encode a dataclass - assuming
you just want all of its attributes, which is what you'd get from a
default implementation. Just encode its __dict__:
>>> @dataclasses.dataclass
... class Demo:
... name: str
... rank: int
... value: int
... def score(self):
... print(f"{self.rank:05d} {self.name} ==> {self.value}")
...
>>> demo = Demo("foo", 1, 23)
>>> demo.score()
00001 foo ==> 23
>>> demo.__dict__
{'name': 'foo', 'rank': 1, 'value': 23}
>>> import json
>>> json.dumps(demo.__dict__)
'{"name": "foo", "rank": 1, "value": 23}'
It'll quietly ignore any methods you've added, and just output the attributes.
ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/3BKVHNC7VL6PR3DPJUFESKFNXAPDMHU4/
Code of Conduct: http://python.org/psf/codeofconduct/