[Python-Dev] Concerns about method overriding and subclassing with dataclasses (original) (raw)

Eric V. Smith eric at trueblade.com
Fri Jan 5 11:43:41 EST 2018


On 1/5/2018 11:24 AM, Guido van Rossum wrote:

On Fri, Jan 5, 2018 at 5:08 AM, Eric V. Smith <eric at trueblade.com_ _<mailto:eric at trueblade.com>> wrote:

On 1/2/2018 12:01 AM, Guido van Rossum wrote: Yes, there's a class variable (dataclassfields) that identifies the parent fields. The PEP doesn't mention this or the fact that special methods (like repr and init) can tell whether a base class is a dataclass. It probably should though. (@Eric)

I think that's covered in this section: https://www.python.org/dev/peps/pep-0557/#inheritance <https://www.python.org/dev/peps/pep-0557/#inheritance> I was specifically talking about the name and contents of dataclassfields, which are not documented by the PEP. I expect it's inevitable that people will be looking at this (since they can see it in the source code). Or do you recommend that people use dataclasses.fields() and catch ValueError?

The expectation is to use dataclasses.fields(). Both it and dataclass_fields contain the fields for this class and the parents. The only difference is the pseudo-fields.

I can add some words describing .fields() returning which fields are present.

I notice that isdataclass() exists but is private and I don't recall why.

I think the argument was that it's an anti-pattern, and if you really want to know, just call dataclasses.fields() and catch the TypeError. I have this in a helper file:

def isdataclass(obj): """Returns True for dataclass classes and instances.""" try: dataclasses.fields(obj) return True except TypeError: return False

(Also now I'm curious what

the "pseudo-fields" are that fields() ignores, but that's OT.)

ClassVar and InitVar "fields". dataclasses.fields() doesn't return them.

Eric.



More information about the Python-Dev mailing list