Advertisement
Intermediate Python, Magic Methods & Operator Overloading

What do __eq__ and __hash__ need to satisfy together, and what happens if you only override __eq__?

Short answer

If two objects are equal (__eq__ returns True), they must have the same hash value so they behave consistently in sets and dict keys.

Save Python mock interview
Advertisement
AModel answer
If two objects are equal (__eq__ returns True), they must have the same hash value so they behave consistently in sets and dict keys. By default, defining __eq__ without __hash__ makes the class unhashable (Python sets __hash__ to None automatically), which raises TypeError if you try to put instances in a set or use them as dict keys.
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)
    def __hash__(self):
        return hash((self.x, self.y))

{Point(1,2)}  # works because __hash__ is defined
Real-world example
A caching layer uses custom key objects as dict keys, so their class must define both __eq__ and __hash__ consistently or lookups will fail unpredictably.
Likely follow-ups
  • Why does Python disable __hash__ when __eq__ is overridden?
  • How does this interact with mutable objects?
Related topics