On Thu, Dec 31, 2020 at 4:29 PM Eric V. Smith <eric@trueblade.com> wrote:
Eric: what do you think about adding a "shallow" (or "deep") flag to dataclasses.asdict()
that would then upack only the top-level dataclass?

Currently a deep copy is made:

Honestly, I'm a bit confused as to why arbitrary types were deep copied in the first place, but maybe that's just evidence that I'm not sure how useful this is in the first place.. or that it's not clear to me what the point was in the first place :-).

I think what we'd want is to just turn the top-level dataclass in to a dict, but then not recurse _and_ only make a shallow copy.

Something like:

>>> asdict(f1, mumble_mumble=False)
{'l': [1, 2, 3], 'f': F(l=[1, 2, 3], f=None)}
>>> asdict(f1)['l'] is mylist
>>> asdict(f1)['f'] is f

Since the 'f' member wouldn't be a copy (I hope there's agreement here), I'd think the 'l' member should also not be a copy.


The question then is: what's a good name for my "mumble_mumble" argument? Does "deep=False" make sense? Or is it "recurse=False"?

When this thread started, I didn't know that it was actually deep copying all members, and had suggested "deep" and "shallow" as analogous to copying. But as it really is doing copying, so i think "deep" and "shallow" are fine.

Which leaves us with ``deep=False`` or ``shallow=True``. I usually prefer the default to be True, but in this case, I still like to thing of "deep" as the special case, so I'd go with: ``deep=False``. or ``deep_copy=False``. 

Or maybe it should just be a separate function. The intent of doing the shallow copy seems different than asdict() currently: asdict() is designed to turn everything to a dict, recursively.

well, yes.

The target is json, but I'm not sure how well it fills that need.

If you ask me, not very well, and there would have been no need to copy lists and the like for that purpose anyway.

JSON-compatible Python is a specific thing -- you are either targeting that or not :-) 

As I said, I don't think asdict() is a great example of API design, and I wish I'd left it out.

Having some convoluted combination of not recursing but making a deep copy seems wrong to me.

agreed on both points :-)

One thing that *might* be useful is a recursing on dataclasses, but not copying anything else :-)

Christopher Barker, PhD (Chris)

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython