-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
dataclasses.astuple (and .asdict) do deepcopy on all fields #88071
Comments
It seems that the 'dataclass.astuple' function does a deepcopy of all fields. This is not documented. Two problems:
->
In my use case, I just want a list of all fields. I can do the following as a workaround: (getattr(foo, field.name) for field in dataclasses.fields(foo)) Tested on Python 3.8.7 and 3.7.9. |
Unfortunately this can't be changed, although I suppose it should be documented. In general I think this API was a mistake, and should not have been added. There are just too many cases where it doesn't do what you want, or where it fails. I'd like to deprecate it and remove it (along with asdict), but I fear that would be too disruptive. Your approach seems reasonable to me for your use case. |
Why deepcopy is used at all? It is a very specific feature which should not be used by default. If you want to make a deep copy of fields, you can call copy.deepcopy() explicitly. copy.deepcopy(dataclasses.astuple(obj)) or dataclasses.astuple(copy.deepcopy(obj)) |
The reason for the deep copying was to support changing a hierarchy of dataclasses into something that could be JSON serialized. But it didn't really work out. It recurses into dataclasses, namedtuples, lists, tuples, and dicts, and deep copies everything else. As I said, it's a design flaw. |
Would it make sense to make dataclasses iterable, like so? def __iter__(self):
return (getattr(self, field.name) for field in fields(self)) With that in place, deprecating astuple would maybe be less disruptive? |
No, iteration is explicitly a non-goal of PEP-557. See the section on namedtuple for why: https://www.python.org/dev/peps/pep-0557/#why-not-just-use-namedtuple |
I've added a PR here: #26154 |
Eric: I've closed a similar issue about asdict() and now updating the title to keep track of both in this issue. Let me know if you want to keep them separate instead. |
I think it's find to address both of these here. |
Thanks, @andrei.avk! |
Thank you for reviewing Eric! |
Update dataclasses.astuple and dataclasses.asdict docstrings to reflect that they deep copy objects in the field values.
…ython#101806) Update dataclasses.astuple and dataclasses.asdict docstrings to reflect that they deep copy objects in the field values.
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
Linked PRs
The text was updated successfully, but these errors were encountered: