I have a parent dataclass and a sub-dataclass inherits the first class. I've redefined __eq__() method in parent dataclass. But when I compare objects sub-dataclass, it doesn't use the __eq__() method defined in parent dataclass. Why is this happening? How can I fix this?
MWE:
from dataclasses import dataclass
@dataclass
class A:
    name: str
    field1: str = None
    def __eq__(self, other):
        print('A class eq')
        return self.name == other.name
@dataclass
class B(A):
    field2: str = None
b1 = B('b', 'b1')
b2 = B('b', 'b2')
print(b1 == b2)
                The @dataclass decorator adds a default __eq__ implementation.
If you use
@dataclass(eq=False)
on class B, it will avoid doing that.
See https://docs.python.org/3/library/dataclasses.html
By default, the dataclass decorator generates an __eq__ method for the decorated class. To disable this (allowing B to inherit A.__eq__), you need to adjust the decorator.
@dataclass(eq=False)
class B(A):
    field2: str = None
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With