-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
gh-91330: Tests and docs for dataclass descriptor-typed fields #94424
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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I left some smaller-scale comments inline but there's a bigger omission in this change: what you are describing only works for data descriptors. Consider this non-data descriptor (doesn't define either __set__
or __delete__
) example:
class NDD:
def __get__(self, obj, type):
if obj is None:
raise AttributeError
return "NDD Internal Value"
@dataclasses.dataclass
class Cls:
ndd: NDD = NDD()
obj = Cls(ndd="Something else!")
print(obj.ndd)
This will print "Something else!" because setting the value will cause ndd
to appear as a key in obj.__dict__
.
While non-data descriptors have little value as dataclass fields, I think it's worth pointing out explicitly that we're talking about data descriptors.
Another thing that irks me is that the example is using obj._x
as internal storage for the data. This means that you cannot have two fields on the same dataclass of type Descriptor
because they will overwrite each other's internal storage. (On the other hand storing state on the object allows it to be trivially picklable.)
Maybe you can come up with a more realistic example. We could also use an example of setting and retrieving a value, both of which would trigger the descriptor. This is currently missing.
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Thanks for your feedback @ambv!
It looks like it only works properly if you have both
Fixed to leverage
I changed the descriptor to convert inputs to
Fixed |
Beautiful! I love the current example. Short but realistically scalable to non-trivial use cases. And includes |
…ythonGH-94424) Co-authored-by: Łukasz Langa <lukasz@langa.pl> (cherry picked from commit 5f31930) Co-authored-by: Erik De Bonte <erikd@microsoft.com>
GH-94576 is a backport of this pull request to the 3.11 branch. |
Sorry, @debonte and @ambv, I could not cleanly backport this to |
…fields (pythonGH-94424) Co-authored-by: Łukasz Langa <lukasz@langa.pl> (cherry picked from commit 5f31930) Co-authored-by: Erik De Bonte <erikd@microsoft.com>
GH-94577 is a backport of this pull request to the 3.10 branch. |
Add unit tests and documentation covering the behaviors of descriptor-typed fields on dataclasses.