Sub topic 4
Equality and Hashing: __eq__ and __hash__
This chapter assumes you can define classes, write instance methods, and use sets and dicts. It covers how == works on your own classes, why __hash__ must match __eq__, and the errors that follow when it doesn't.
Default behavior
By default, == on instances compares identity. Two separate objects are never equal, even when their attributes match.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
print(Point(1, 2) == Point(1, 2)) # FalseTo compare by value, define __eq__. Python calls a == b as a.__eq__(b).
Writing __eq__
Check the other object's type first. If it isn't one you understand, return NotImplemented instead of False. Python then tries the other operand's __eq__, and falls back to identity comparison if neither side knows the type.
Why __hash__ comes with it
A set or dict uses an object's hash to find the slot where it is stored, then uses == to confirm a match. Two equal objects must therefore have equal hashes. Otherwise a lookup can land in the wrong slot and miss an object that is equal.
Python enforces this in one direction. When you define __eq__ and not __hash__, Python sets __hash__ to None, and instances become unhashable.
class Broken:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, Broken) and self.x == other.x
try:
{Broken(1)}
except TypeError as e:
print(e) # unhashable type: 'Broken'The fix is to define __hash__ from the same fields that __eq__ compares.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
v = Vector(1, 2)
print(v) # Vector(1, 2)
print(v == Vector(1, 2)) # True
print(len({v, Vector(1, 2)})) # 1Hashing a tuple of the compared fields keeps the two methods in step.
Common errors
- Mutable fields in the hash. If an object's hash changes while it sits in a set or is a dict key, lookups fail. Hash only fields that never change, or treat the object as immutable.
- Hash and equality out of sync. If
__eq__comparesxandybut__hash__uses onlyx, that is still valid, because equal objects keep equal hashes. Hashing a field that__eq__ignores is the real bug, since equal objects then get different hashes. - Returning
Falsefor foreign types. This blocks the other operand from handling the comparison. ReturnNotImplemented.
Exercise
A class defines __eq__ comparing self.name, and __hash__ returning hash((self.name, self.age)). Is this correct? Why or why not?
Show answer
No. Two objects with the same name but different ages are equal under __eq__ yet have different hashes. This breaks the rule that equal objects must have equal hashes, so a set could hold both as separate entries. Hash only self.name, or compare age in __eq__ too.