Sub topic 11
Keys: the equality and hash contract
This chapter assumes you know what a hash set and a hash map do, and that a hash function turns a key into an integer used to pick a bucket. Here we look at what a key must promise so that lookups find what you stored.
The contract
A hash table does two things with a key. It calls the hash function to choose a bucket. Then it compares keys with equality inside that bucket. For this to work, the key type must follow one rule:
- If two keys are equal, their hashes must be equal.
The reverse is not required. Two different keys may share a hash. That is a collision, and equality sorts it out inside the bucket.
The rule also implies two stability requirements. A key's hash must not change while it is in the table. Equality must stay consistent too: if a == b once, it must keep being true.
Why a broken contract loses entries
Suppose two keys are equal but hash differently. The table looks in the bucket for the second key's hash. The stored entry sits in a different bucket, so the lookup reports a miss even though an equal key is present.
You can see this with a class that defines equality but not a matching hash:
class Bad:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, Bad) and self.n == other.n
def __hash__(self):
return id(self) # differs per object, so equal objects hash differently
seen = {Bad(1)}
print(Bad(1) == Bad(1)) # True
print(Bad(1) in seen) # False (almost always)The two objects are equal, yet the set cannot find one using the other. The fix is to compute the hash from the same fields that equality uses.
class Good:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, Good) and self.n == other.n
def __hash__(self):
return hash(self.n)
seen = {Good(1)}
print(Good(1) in seen) # TrueLetting a dataclass do it
Writing both methods by hand invites mistakes. A frozen dataclass generates equality and a matching hash from its fields.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
visited = {Point(1, 2)}
print(Point(1, 2) in visited) # TrueTwo Point objects with the same fields are different objects but equal keys, so the set finds the stored one.
What makes a good key
Prefer keys that are immutable and compared by value. Strings, numbers, tuples of those, and frozen dataclasses all qualify. Python refuses mutable built-in containers as keys:
try:
table = {[1, 2]: "x"}
except TypeError as e:
print(e) # unhashable type: 'list'A list could change after insertion. Its hash would change with it, and the entry would sit in the wrong bucket. Use a tuple instead when you need a sequence as a key.
Common errors
| Mistake | Effect |
|---|---|
| Equal objects with different hashes | Lookups miss entries that are present |
| Hash built from fields that equality ignores | Same as above |
| Hash built from mutable fields | Entries are lost after the object changes |
| `__eq__` that is not symmetric or stable | Unpredictable matches |
| Constant hash such as `return 1` | Correct, but every key collides and operations slow to linear |
The last row is allowed by the contract. A hash that is the same for all keys is valid but removes the speed benefit.
Exercise
A class defines __eq__ to compare a name field and an age field, and __hash__ as hash(self.name). Does this satisfy the contract? What happens if __hash__ instead returns hash(self.age) while equality compares only name?
Show answer
The first version satisfies the contract. Equal objects have the same name, so they have the same hash. Objects with the same name but different ages are unequal and may collide, which is allowed. The second version breaks it. Two objects with the same name are equal but can have different ages, so they hash differently and lookups can miss a stored equal key.