[Python-ideas] add an additional dataclasses.asdict option for non-dataclasses

Ricky Teachey ricky at teachey.org
Fri May 3 12:37:56 EDT 2019


I just joined the ideas list today so I do not know if this has been
discussed.

Using dataclasses has been great for me, but a challenge is what to do when
you don't *know* if the object you are using is a dataclass, and could be a
variety of other classes.

This could easily occur when you don't want to assume the data type being
used by the user to represent their data, but wish to turn it into a dict
(if an API exists to do so).

Currently, you have to do something like this when you don't know if your
object is a dataclass instance (I am using "dict_factory" since that is
already the asdict() keyword arg):

d = asdict(obj) if is_dataclass(obj) else dict_factory(obj)

If it could also be a namedtuple, you might write this:

d = asdict(obj) if is_dataclass(obj) else obj._asdict() if isinstance(obj,
namedtuple) else dict_factory(obj)

and if it could also be some other object with an .asdict() method:

d = asdict(obj) if is_dataclass(obj) else obj._asdict() if isinstance(obj,
namedtuple) else obj.asdict() if hasattr(obj, "asdict")
else dict_factory(obj)

This gets pretty silly/unwieldy somewhat quickly.

The idea is: 1. identifying the various "asdict" APIs used in the standard
library, and 2. include a keyword option for dataclasses.asdict() to cast a
non-dataclasses object to a dict using these protocols (and falling back on
factory_dict(obj) if it is provided).


---
Ricky.

"I've never met a Kentucky man who wasn't either thinking about going home
or actually going home." - Happy Chandler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190503/270104f8/attachment.html>


More information about the Python-ideas mailing list