On 12/9/2020 10:39 AM, Chris Angelico wrote:
On Thu, Dec 10, 2020 at 12:38 AM sam bland <sbland.co...@gmail.com> 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.
The dataclass metadata feature was added for this type of use, or at
least experimenting with it:
-----
import json
import dataclasses
@dataclasses.dataclass
class Demo:
name: str
rank: int
value: int = dataclasses.field(metadata={"json": False})
def serialize(o):
return json.dumps(
{
k: getattr(o, k)
for k, v in o.__dataclass_fields__.items()
if v.metadata.get("json", True)
}
)
print(serialize(Demo("foo", 1, 23)))
----
Prints:
{"name": "foo", "rank": 1}
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/5EMW7D24UMFUL24NWBHPXMBTXY5RCYS2/
Code of Conduct: http://python.org/psf/codeofconduct/