Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataclass not inheriting __eq__() method from its parent

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)
like image 365
Nagabhushan S N Avatar asked Apr 25 '20 18:04

Nagabhushan S N


2 Answers

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

like image 177
khelwood Avatar answered Oct 10 '22 21:10

khelwood


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
like image 39
chepner Avatar answered Oct 10 '22 22:10

chepner