Sub topic 12
Mutable keys and lost entries
This chapter assumes you know how a hash table places a key in a bucket, and that a key's hash and equality must agree. If either idea is shaky, review the chapters on hash tables and the key contract first.
Why a stored key must not change
A hash table finds an entry by computing hash(key) and then jumping to the matching bucket. The entry is filed under the hash the key had when it was inserted. Suppose the key's contents change afterward, and so does its hash. A later lookup computes the new hash, goes to a different bucket, and finds nothing. The entry still exists in the table, but no lookup can reach it.
Python guards against this for its built-in containers. A list has no hash, so it cannot be a key:
try:
table = {[1, 2]: "x"}
except TypeError as e:
print(e) # unhashable type: 'list'The usual fix is an immutable equivalent. Use a tuple instead of a list, or a frozenset instead of a set.
Breaking it on purpose
Python lets you write a mutable class that defines __hash__ from its fields. That bypasses the safeguard, and the failure is quiet:
class Tag:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return isinstance(other, Tag) and self.name == other.name
def __hash__(self):
return hash(self.name)
tag = Tag("python")
seen = {tag}
print(tag in seen) # True
tag.name = "java" # mutate the key while it is stored
print(tag in seen) # False: the lookup now hashes "java"
print(len(seen)) # 1: the entry is still there
print(Tag("python") in seen) # Usually False: the hash matches, but the stored key now equals "java"The set still holds one element, so len reports 1. The element can't be found by its old value or its new one. In the last check, the hash leads to the right bucket, but the stored key now compares unequal. In the check before it, the new hash leads to a bucket that holds nothing. Either way the lookup fails.
Common errors
- Hashing mutable fields. Defining
__hash__from fields that can change is the root cause. Hash only fields that never change after construction. - Mutating after insertion. Even a correctly designed key breaks if someone edits it in place while it sits in the table.
- Shared references. A key object may be referenced from elsewhere in the program. A change made through that other reference corrupts the table with no warning at the point of insertion.
- Mutable values inside a tuple. A tuple is hashable only if its elements are.
({}, 1)raisesTypeErrorwhen hashed, because the dict inside is unhashable.
Safe designs
- Make key types immutable. A frozen dataclass does this, since assigning to a field raises
FrozenInstanceError. - Convert at the boundary. Build a tuple or
frozensetfrom the mutable data before using it as a key. - If an object must change, remove it, change it, then insert it again.
tag = Tag("python")
seen = {tag}
seen.remove(tag) # remove while the hash is still correct
tag.name = "java"
seen.add(tag) # re-insert under the new hash
print(tag in seen) # TrueExercise
A set of Tag objects, where Tag hashes its name, contains one tag. You change that tag's name in place. Why does len(seen) still return 1 while tag in seen returns False, and how should you rename the tag safely?
Show answer
The entry is still stored in the bucket chosen by the old hash, so the size is unchanged. The membership check hashes the new name, looks in a different bucket, and finds nothing. To rename safely, remove the tag before changing it, change the name, then add it again. A better design makes Tag immutable (for example, a frozen dataclass), so renaming creates a new object.