What Is __ Eq __ In Python

5 min read

What Is __eq__ in Python: A Complete Guide to Equality Comparison

The __eq__ in Python is a special method (also called a dunder or magic method) that defines how objects compare for equality using the == operator. Here's the thing — whenever you write object_a == object_b, Python quietly calls object_a. Day to day, __eq__(object_b) behind the scenes. Now, understanding this method is essential for anyone who wants to build custom classes that behave predictably, sort correctly, and integrate smoothly with Python's data structures. This guide walks you through what __eq__ does, how to implement it properly, and the subtle rules that trip up even experienced developers.

Introduction: Why Equality Is More Than ==

At first glance, comparing two values in Python seems trivial. Practically speaking, numbers compare by value, strings compare character by character, and lists compare element by element. Are they "equal"? But the moment you create your own class, equality stops being automatic. Consider two Point objects with the same coordinates. By default, Python says no, because it compares their memory identities rather than their contents.

This is where __eq__ becomes powerful. In practice, it lets you decide what equality means for your objects. Whether you are modeling a bank account, a geometric shape, or a database record, __eq__ gives you control over how instances relate to one another. Mastering it is a small investment that pays off in cleaner code, reliable testing, and intuitive APIs.

What Exactly Is __eq__?

__eq__ is a dunder method, short for "double underscore" method, named for the two underscores on each side. These methods are not called directly by name in everyday code; instead, Python invokes them automatically in response to specific operations or built-in functions.

Specifically, __eq__(self, other) is triggered by the equality operator ==. The method receives two arguments:

  • self: the object on the left side of ==.
  • other: the object on the right side of ==.

The method is expected to return either True, False, or the special value NotImplemented. Returning NotImplemented signals to Python that the comparison is not supported between the two types, allowing Python to try the reflected operation on the other object before giving up.

The Default Behavior Without __eq__

If you do not define __eq__, Python falls back to identity comparison. This means two objects are considered equal only if they are literally the same object in memory, which you can check with the is operator.

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

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)  # False
print(p1 is p2)  # False

Even though p1 and p2 hold identical data, p1 == p2 returns False. This surprises many beginners, and it is the primary reason __eq__ exists Nothing fancy..

How to Implement __eq__ Correctly

To make two Point objects compare by value, you define __eq__ to check the relevant attributes:

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.And x == other. Consider this: x and self. y == other.

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)  # True

Notice two important practices here:

  1. Type checking with isinstance: This guards against comparing a Point with an unrelated type, preventing confusing errors.
  2. Returning NotImplemented: Instead of raising an exception or returning False outright, returning NotImplemented lets Python handle the comparison gracefully.

The Scientific Explanation: How Python Resolves ==

When you evaluate a == b, Python follows a well-defined sequence:

  • It first calls a.__eq__(b).
  • If that returns NotImplemented, Python tries the reflected method b.__eq__(a).
  • If both return NotImplemented, Python falls back to identity comparison, effectively checking a is b.

This two-sided attempt is why implementing __eq__ thoughtfully matters. A well-behaved __eq__ should be:

  • Reflexive: a == a should always be True.
  • Symmetric: if a == b is True, then b == a should also be True.
  • Transitive: if a == b and b == c, then a == c should be True.

Violating these properties leads to subtle bugs, especially when objects are stored in sets or used as dictionary keys.

The Connection Between __eq__ and __hash__

A frequently overlooked rule links equality and hashing. If you define __eq__ in a class, Python sets __hash__ to None, making instances unhashable by default. This means you cannot place them in a set or use them as keys in a dict until you also define __hash__ Most people skip this — try not to..

The guiding principle is simple: objects that compare equal must have the same hash value. If you need your objects to be hashable, define both methods together:

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.Also, x and self. y == other.

    def __hash__(self):
        return hash((self.x, self.y))

Related Comparison Methods

__eq__ does not work alone. It is part of a family of rich comparison methods:

  • __ne__(self, other): defines !=. If you do not define it, Python often derives it from __eq__ automatically.
  • __lt__, __le__, __gt__, __ge__: define <, <=, >, and >= for ordering.

If your class needs full ordering, the functools.total_ordering decorator can fill in the remaining methods from __eq__ and one ordering method, saving you repetitive code.

Practical Shortcuts: Dataclasses

Modern Python offers a convenient shortcut. The @dataclass decorator can generate __eq__ for you automatically based on the class fields:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)  # True

By default, dataclass sets eq=True, producing a value-based __eq__. This is ideal for simple data containers where field-by-field comparison is exactly what you want.

Common Mistakes to Avoid

  • Comparing different types carelessly: Always check types or return NotImplemented to keep comparisons predictable.
  • **Forgetting
Newly Live

Just Finished

Along the Same Lines

A Natural Next Step

Thank you for reading about What Is __ Eq __ In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home