ZetCode

Python __eq__ Method

Last modified November 17, 2026 Python 3.15

The == operator calls __eq__ on the left operand, and Python may also try the reflected method on the right operand. A good implementation returns NotImplemented for unsupported types, keeps the comparison laws, and stays consistent with __hash__. This article shows the dispatch, custom rules, inheritance, hashing, and a case-insensitive string type.

How == calls __eq__

a == b is evaluated as type(a).__eq__(a, b). The hook should return True or False, or NotImplemented when it does not recognise the other type. Returning NotImplemented lets Python try the reflected method before falling back to identity comparison.

basic_eq.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y


p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(3, 4)
print(p1 == p2)
print(p1 == p3)
print(p1 == "not a point")

Points with equal coordinates compare equal, different points do not, and comparing a point with a string yields False rather than an error. That last result comes from the NotImplemented return: the string's own comparison also declines, so Python falls back to identity.

$ python basic_eq.py
True
False
False

Returning NotImplemented

When the left operand's __eq__ returns NotImplemented, Python calls the right operand's __eq__ with the arguments reversed. This is the reflected comparison, and it is what makes mixed-type comparisons work in both directions.

notimplemented_eq.py
class Left:
    def __eq__(self, other):
        print("Left.__eq__")
        return NotImplemented


class Right:
    def __eq__(self, other):
        print("Right.__eq__")
        return True


print(Left() == Right())
print(Right() == Left())

In Left() == Right() both methods are called: the first declines and the second returns True. In Right() == Left() the left method answers immediately, so only one line is printed. Returning NotImplemented is not the same as returning False: the latter ends the comparison.

$ python notimplemented_eq.py
Left.__eq__
Right.__eq__
True
Right.__eq__
True

Business rules

Equality does not have to compare every field. A class can define what “the same object” means for its domain, as long as the result is consistent.

business_eq.py
class Account:
    def __init__(self, number, balance):
        self.number = number
        self.balance = balance

    def __eq__(self, other):
        if not isinstance(other, Account):
            return NotImplemented
        return self.number == other.number

    def __repr__(self):
        return f"Account({self.number!r}, {self.balance})"


a1 = Account("12345", 1000)
a2 = Account("12345", 500)
a3 = Account("67890", 1000)
print(a1 == a2)
print(a1 == a3)

Two accounts with the same number are equal even when their balances differ; a different number makes them unequal. The __repr__ method is only for debugging and plays no part in the comparison.

$ python business_eq.py
True
False

Equality and inheritance

Using isinstance inside __eq__ means a base-class instance can compare equal to a subclass instance. Whether that is desirable depends on whether the subclass adds distinguishing state.

inheritance_eq.py
class Vehicle:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def __eq__(self, other):
        if not isinstance(other, Vehicle):
            return NotImplemented
        return self.make == other.make and self.model == other.model


class Car(Vehicle):
    def __init__(self, make, model, doors):
        super().__init__(make, model)
        self.doors = doors


v = Vehicle("Toyota", "Camry")
c = Car("Toyota", "Camry", 4)
print(v == c)
print(c == v)

Here Car shares its parent's __eq__, so a plain Vehicle and a Car with the same make and model compare equal in both directions. If a subclass adds state that must be compared, it should override __eq__ and call super().

$ python inheritance_eq.py
True
True

Requiring the exact type

When a subclass must never equal its parent, compare type(other) is type(self) instead of using isinstance. Returning NotImplemented for the mismatched type still allows the other operand to answer.

strict_eq.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if type(other) is not type(self):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)


class Point3D(Point):
    def __init__(self, x, y, z):
        super().__init__(x, y)
        self.z = z


p = Point(1, 2)
q = Point3D(1, 2, 3)
print(p == q)
print(q == p)
print(p == Point(1, 2))

A Point is no longer equal to a Point3D that happens to share its coordinates, while two ordinary points remain equal. The check is symmetric because both classes use the same rule.

$ python strict_eq.py
False
False
True

Equality and hashing

Python assumes that objects which compare equal have equal hashes. A class that defines __eq__ without __hash__ becomes unhashable, so define both when instances go into a set or a dictionary key. The rule must use the same fields as equality.

hash_eq.py
class Product:
    def __init__(self, pid, name):
        self.pid = pid
        self.name = name

    def __eq__(self, other):
        if not isinstance(other, Product):
            return NotImplemented
        return self.pid == other.pid

    def __hash__(self):
        return hash(self.pid)

    def __repr__(self):
        return f"Product({self.pid}, {self.name!r})"


a = Product(1, "Laptop")
b = Product(1, "Laptop Pro")
c = Product(2, "Mouse")
print(a == b, hash(a) == hash(b))
print({a, b, c})
print(len({a, b, c}))

The two products with id 1 are equal and share a hash, so the set keeps only one of them; the printed set has two members. Using a field in __eq__ but not in __hash__, or the other way around, would break the collection.

$ python hash_eq.py
True True
{Product(1, 'Laptop'), Product(2, 'Mouse')}
2

A case-insensitive string

A custom class can compare against its own type and against built-in strings. Handling both directions and returning NotImplemented for anything else keeps the behaviour predictable.

case_eq.py
class CIString:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        if isinstance(other, str):
            return self.value.lower() == other.lower()
        if isinstance(other, CIString):
            return self.value.lower() == other.value.lower()
        return NotImplemented


s = CIString("Hello")
print(s == CIString("hello"))
print(s == "HELLO")
print("WORLD" == CIString("world"))

All three comparisons are true. The last one works because str.__eq__ returns NotImplemented for an unknown type, giving CIString.__eq__ a chance to answer. Such an object should not be used as a dictionary key unless __hash__ follows the same case-folding rule.

$ python case_eq.py
True
True
True

Best practices

Equality is used by many library functions, so keep its rules predictable:

Source

object.__eq__ - Python documentation

object.__hash__ - Python documentation

hash() - Python documentation

In this article we have implemented the __eq__ method. We have covered the == dispatch, NotImplemented, business rules, inheritance, hashing, and a case-insensitive string. For related topics, see Python __ne__ method, Python __hash__ method, and Python __lt__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.