[Python-Dev] Second post: PEP 557, Data Classes (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Tue Nov 28 07:02:25 EST 2017
- Previous message (by thread): [Python-Dev] Second post: PEP 557, Data Classes
- Next message (by thread): [Python-Dev] Second post: PEP 557, Data Classes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 28 November 2017 at 17:41, Eric V. Smith <eric at trueblade.com> wrote:
One thing this doesn't let you do is compare instances of two different subclasses of a base type:
@dataclass class B: i: int @dataclass class C1(B): pass @dataclass class C2(B): pass You can't compare C1(0) and C2(0), because neither one is an instance of the other's type. The test to get this case to work would be expensive: find the common ancestor, and then make sure no fields have been added since then. And I haven't thought through multiple inheritance. I suggest we don't try to support this case.
That gets you onto problematic ground as far as transitivity is concerned, since you'd end up with the following:
>>> b = B(0); c1 = C1(0); c2 = C2(0)
>>> c1 == b
True
>>> b == c2
True
>>> c1 == c2
False
However, I think you can fix this by injecting the first base in the MRO that defines a data field as a "field_layout" class attribute, and then have the comparison methods check for "other.field_layout is self.field_layout", rather than checking the runtime class directly.
So in the above example, you would have:
B.field_layout is B True C1.field_layout is B True C2.field_layout is B True
It would then be up to the dataclass decorator to set
__field_layout__
correctly, using the follow rules:
- Use the just-defined class if the class defines any fields
- Use the just-defined class if it inherits from multiple base classes that define fields and don't already share an MRO
- Use a base class if that's either the only base class that defines fields, or if all other base classes that define fields are already in the MRO of that base class
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message (by thread): [Python-Dev] Second post: PEP 557, Data Classes
- Next message (by thread): [Python-Dev] Second post: PEP 557, Data Classes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]