Full answer
class Badge:
def __init__(self, code): self.code = code
def __eq__(self, other): return isinstance(other, Badge) and self.code == other.code
def __hash__(self): return hash(self.code)
b = Badge("A1")
owners = {b: "Asha"}
b.code = "Z9"
print(Badge("A1") in owners, Badge("Z9") in owners, len(owners))
print([k.code for k in owners])
from dataclasses import dataclass
@dataclass(frozen=True)
class SafeBadge:
code: str
s = SafeBadge("A1")
print({s: "Asha"}[SafeBadge("A1")])Output:
False False 1
['Z9']
AshaAfter b.code changes, the dict still stores the entry in the bucket for the old hash. Looking up Badge('A1') finds the bucket but the stored key no longer compares equal; looking up by the new code hashes to a different bucket. The entry is effectively lost although len(owners) is still 1 and iteration shows it. Even looking up with the same object b is unreliable: CPython checks identity first, so it succeeds only if the new hash happens to probe the old slot, which depends on the hash seed. The double run of this item caught exactly that, which is why the check is left out of the printout. A frozen dataclass makes the key immutable and generates a consistent __hash__ and __eq__. Python sets __hash__ to None when a class defines __eq__ alone, which prevents half of this mistake by default.
class Badge:
def __init__(self, code): self.code = code
def __eq__(self, other): return isinstance(other, Badge) and self.code == other.code
def __hash__(self): return hash(self.code)
b = Badge("A1")
owners = {b: "Asha"}
b.code = "Z9"
print(Badge("A1") in owners, Badge("Z9") in owners, len(owners))
print([k.code for k in owners])
from dataclasses import dataclass
@dataclass(frozen=True)
class SafeBadge:
code: str
s = SafeBadge("A1")
print({s: "Asha"}[SafeBadge("A1")])Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Equal objects need equal hashes
- Hashes must not change while stored
- Mutating keys loses entries
- Frozen dataclasses give safe keys
- Defining __eq__ alone disables hashing
Common mistakes
- Hashing mutable fields
- Defining __hash__ inconsistent with __eq__
Follow-ups
- Why are lists unhashable but tuples hashable?
- How are dict lookups implemented?
Tips
- Explain the bucket lookup