Sub topic 4
Equality and hashing: `__eq__` and `__hash__`
This chapter assumes you can define classes with __init__ and regular methods, and that you know how set and dict are used. You should also have read the earlier chapter on __repr__, since the examples use it to show results.
Default equality is identity
A new class gets == behavior inherited from object. That behavior compares identity: two names are equal only if they refer to the same object.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
a = Point(1, 2)
b = Point(1, 2)
print(a == a) # True
print(a == b) # False, different objects
print(a != b) # TrueFor a value-like class such as a point, a vector or a version number, this is rarely what you want. Two points with the same coordinates should be equal. You get that by defining __eq__.
Defining `__eq__`
When Python evaluates a == b, it calls type(a).__eq__(a, b). The method should return True or False for operands it understands. For anything else it should return NotImplemented. Do not return False for unknown types, and do not raise an exception.
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)
print(Vector(1, 2) == Vector(1, 2)) # True
print(Vector(1, 2) == (1, 2)) # False
print(Vector(1, 2) != Vector(3, 4)) # TrueThree details are worth knowing:
!=needs no method of its own. The default__ne__calls__eq__and inverts the result, unless that result isNotImplemented.- When
__eq__returnsNotImplemented, Python tries the reflected call,other.__eq__(self). If that also returnsNotImplemented, Python falls back to an identity comparison. That is whyVector(1, 2) == (1, 2)printsFalsewithout any error. - Comparing tuples of fields keeps
__eq__short. It also keeps the fields in one place, so you can reuse the same tuple in__hash__.
Defining `__eq__` removes hashing
Here is the most common surprise. If a class defines __eq__ and does not define __hash__, Python sets __hash__ to None. The instances become unhashable.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
try:
{Vector(1, 2)}
except TypeError as e:
print(e) # unhashable type: 'Vector'Python does this on purpose. The default hash is based on identity. If it were kept, two equal vectors would have different hashes, and sets and dicts would behave wrongly.
The hash contract
A hash is an integer that set and dict use to find an object quickly. Your __hash__ must follow this rule:
- If
a == b, thenhash(a) == hash(b).
The reverse does not have to hold. Different objects may share a hash, which is called a collision. The container then uses == to tell them apart.
The usual way to meet the rule is to hash a tuple of exactly the 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)})) # 1
print({v: 'a'}[Vector(1, 2)]) # aThe built-in types follow the same rule across types. 1 == 1.0 is True, so hash(1) == hash(1.0), and {1: 'a'}[1.0] returns 'a'.
The next diagram shows what happens during x in s. The hash comes first and == second, so a wrong hash makes a lookup fail before __eq__ is ever called.
Mutable objects and hashes
A hash must not change while the object is stored in a set or used as a dict key. The container remembers the hash from the moment of insertion. If you change the fields afterward, the object is filed under a hash that no longer matches it.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
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)
s = {v}
v.x = 10
print(v in s) # False, the stored hash no longer matches
print(len(s)) # 1, the object is still in the setThe object is still in the set, but you can no longer find it. There are three common fixes:
- Make the class immutable by convention. Use read-only properties or
__slots__, and never reassign the fields. - Hash only fields that never change, such as an ID, and compare the same fields in
__eq__. - Leave the class unhashable. If instances are meant to change,
__hash__ = Noneis a legitimate and honest choice. Built-inlist,dictandsetdo the same.
Equality and inheritance
Using isinstance(other, Vector) means a subclass instance can compare equal to a base-class instance. That is often fine. If it is not, compare exact types instead:
def __eq__(self, other):
if type(other) is not type(self):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)A subclass that overrides __eq__ loses the inherited __hash__ for the same reason as before. Restore it with __hash__ = Base.__hash__, or write a new one that matches the new __eq__.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: unhashable type` | `__eq__` defined without `__hash__` | Add `__hash__`, or accept that the class is unhashable |
| Equal objects appear twice in a set | `__hash__` uses different fields than `__eq__`, or the default identity hash is still in use | Hash the same fields that `__eq__` compares |
| Object cannot be found after a change | Hashed field was mutated while stored | Make the fields immutable or exclude them from the hash |
| `==` raises `AttributeError` on other types | `__eq__` reads attributes without a type check | Return `NotImplemented` for unsupported types |
| `==` with an unrelated type quietly gives `False` | Both sides returned `NotImplemented` | This is expected behavior, not a bug |
Summary of the rules
- Define
__eq__to returnNotImplementedfor operand types you do not handle. - Define
__hash__whenever you define__eq__and the instances should be hashable. Hash the same fields that__eq__compares. - Keep hashed fields unchanged for as long as an object lives in a set or dict.
- Do not define
__ne__unless you need behavior the default cannot give you.
Exercise
A class defines __eq__ comparing self.id and other.id, and defines __hash__ as hash((self.id, self.name)). Two objects have the same id but different name. What goes wrong when you put both in a set, and how do you fix it?
Show answer
The two objects are equal (same id), but their hashes differ because name is part of the hash. This breaks the rule that equal objects must have equal hashes, so the set may keep both as separate entries. The fix is to hash exactly the fields used by __eq__: __hash__ should return hash(self.id).
Exercise
What does Vector(1, 2) == (1, 2) print if Vector.__eq__ returns NotImplemented for non-Vector operands, and why is no exception raised?
Show answer
It prints False. Python first calls Vector.__eq__, which returns NotImplemented. It then tries the reflected tuple.__eq__, which also returns NotImplemented. With both sides declining, Python falls back to comparing identity, and the two objects are different, so the result is False.