[Python-ideas] add an additional dataclasses.asdict option for non-dataclasses
rhodri at kynesim.co.uk
Fri May 3 13:00:46 EDT 2019
On 03/05/2019 17:37, Ricky Teachey wrote:
> I just joined the ideas list today so I do not know if this has been
> 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).
Conventionally you would get the caller to do this, because only the
caller knows what format they have actually got. Anything else involves
lots of guesswork and, as you point out, gets unweildy and silly very
> 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).
Are "asdict" APIs all that common? I can't recall feeling much need for
them, but I'm hardly a good test case :-)
The problem with "casting" a generic non-dataclass object to a dict is
that it's not remotely obvious how you do that. What key do you use if
your object is a simple int or string? If you have even a
straightforward user class aren't just using "thing.__dict__", what
attributes do or do not make it into the dictionary?
I'm sorry, but I'm not convinced that this is a rabbit-hole that it will
be useful to dive down.
Rhodri James *-* Kynesim Ltd
More information about the Python-ideas