Custom Keys and Adversarial Inputs
Apply Python hashability rules (__hash__, __eq__, and frozen dataclasses), diagnose unhashable custom classes and mutable-field traps, and see how colliding keys and HashDoS degrade O(1) operations to O(n).
Contentsand lesson path
On this page
- Why it matters
- What makes a key hashable: __hash__, __eq__ and immutability
- When O(1) degrades to O(n)—and CPython HashDoS limits
- Check your understanding
- Apply it
- Review prompt
Lessons of Hashing & Hash Tables
- From Keys to Buckets Concept · 20 min
- Collisions, Load Factor and Resizing Concept · 20 min
- Lab: Build a Chained Hash Map Lab · 30 min
- Counting, Grouping and Complement Lookups Worked example · 25 min
- Custom Keys and Adversarial Inputs Concept · 15 min
- Check: Hashing Problem Set Knowledge check · 8 questions
What you will learn
- Explain when hash operations degrade to O(n) and what makes a key hashable, including consistent __hash__ and __eq__ on custom classes.
Prerequisites: Complexity Analysis
01. Why it matters
You add __eq__ to a Point class so Point(1, 2) == Point(1, 2) returns True, insert an instance into a set, and Python immediately raises TypeError: unhashable type: 'Point'—even though a plain class without __eq__ went into a set without complaint! On another day, a hash-backed endpoint stalls under a crafted payload even though automatic resizing is active.
Both surprises come from Python's hashability contract and the gap between average-case and worst-case hashing. Knowing the Python 3.12 data model rules lets you build valid custom keys, avoid silent lost-key bugs, and recognise when colliding or adversarial inputs degrade O(1) lookups to O(n).
02. What makes a key hashable: __hash__, __eq__ and immutability
Recall from Collisions, Load Factor and Resizing that a hash table places a key using hash(key) at insertion time and later probes using hash(key) again. That enforces two strict rules:
- Stable hash over key lifetime: if a mutable key such as a
listchanged contents after insertion, its hash would change while the entry stayed parked in the old bucket—making the entry unreachable on future lookups. That is why mutable built-ins (list,dict,set) refuse to hash and raiseTypeError. - Equality implies equal hashes: whenever
a == bisTrue, Python requireshash(a) == hash(b). (The reverse is not required: unequal keys may share a hash.)
A plain class without __eq__ inherits object.__eq__ (identity comparison is) and object.__hash__ (derived from identity). The moment you define __eq__ without __hash__, Python 3 cannot safely keep the inherited identity hash because two separate Point(1, 2) objects would compare equal yet return different hashes! To prevent silent key loss, Python 3 automatically sets __hash__ = None, making isinstance(obj, collections.abc.Hashable) return False.
The safest fix for value keys is @dataclass(frozen=True): it blocks attribute reassignment (FrozenInstanceError), generates value-based __eq__, and generates a matching __hash__ over the field tuple. Watch one subtle trap: frozen=True only prevents rebinding an attribute (route.ports = ...); it does not make nested mutable objects immutable! If you declare @dataclass(frozen=True) class Route: host: str; ports: list[int], calling hash(Route("api", [80, 443])) raises TypeError: unhashable type: 'list' because tuple hashing recursively hashes every field—and even if a hand-written __hash__ ignored ports, mutating route.ports.append(8080) would break equality against __hash__. Always use immutable field types such as tuple[int, ...] for sequence fields.
If you write a regular class by hand instead of using @dataclass(frozen=True), keep every field read inside __eq__ read-only (for instance via private attributes with @property getters) and write def __hash__(self) -> int: return hash((self.x, self.y)) over the exact same tuple of fields. Never define __hash__ on a class whose equality fields can change after insertion, because hashed containers never re-index existing keys when attributes mutate.
from collections.abc import Hashable
from dataclasses import dataclass
import sys
class BadPoint:
def __init__(self, x: int, y: int) -> None:
self.x, self.y = x, y
def __eq__(self, other: object) -> bool:
if not isinstance(other, BadPoint):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
@dataclass(frozen=True)
class GoodPoint:
x: int
y: int
class ConstantHashKey:
eq_calls = 0
def __init__(self, label: str) -> None:
self.label = label
def __eq__(self, other: object) -> bool:
ConstantHashKey.eq_calls += 1
return isinstance(other, ConstantHashKey) and self.label == other.label
def __hash__(self) -> int:
return 42
print("BadPoint hashable?", isinstance(BadPoint(1, 2), Hashable))
try:
_ = {BadPoint(1, 2)}
except TypeError as exc:
print("BadPoint set error:", exc)
pts = {GoodPoint(1, 2), GoodPoint(1, 2)}
print("GoodPoint set:", pts, "len=", len(pts))
print("hash_info:", sys.hash_info.algorithm, "width:", sys.hash_info.width)
m = sys.hash_info.modulus
print("int hash collision across runs:", hash(42), hash(2 * m + 42))
ConstantHashKey.eq_calls = 0
colliders = {ConstantHashKey(f"k{i}"): i for i in range(200)}
print("colliders len:", len(colliders), "eq_calls for 200 inserts:",
ConstantHashKey.eq_calls)BadPoint hashable? False
BadPoint set error: unhashable type: 'BadPoint'
GoodPoint set: {GoodPoint(x=1, y=2)} len= 1
hash_info: siphash13 width: 64
int hash collision across runs: 42 42
colliders len: 200 eq_calls for 200 inserts: 2008903. When O(1) degrades to O(n)—and CPython HashDoS limits
Look at ConstantHashKey above: returning 42 obeys a == b => hash(a) == hash(b), so Python inserts all 200 keys cleanly—yet inserting just 200 keys triggered 20,089 calls to __eq__! Why? During lookup or insert, CPython checks each candidate slot by comparing the stored full hash first (entry.hash == target_hash) and only calls __eq__ when the two hashes match and the keys are not identical by is. For 200 distinct GoodPoint keys with spread hashes, hash mismatches reject wrong slots without calling __eq__ (0 calls on distinct keys). When every key returns hash 42, every key computes the exact same starting slot and the exact same perturb probe path, forcing each new insert to walk past all earlier entries calling __eq__ (~n*(n-1)/2 comparisons, or O(n^2) total work, making each lookup O(n)). Notice that resizing does nothing to separate keys whose hash() values are identical, and unlike Java HashMap (which converts overly long buckets into balanced trees), Python dict and set never switch to trees.
The same slowdown strikes untrusted inputs if an attacker can predict collisions (HashDoS), such as sending thousands of JSON keys or HTTP form parameters that all land on one probe path. To defend str and bytes keys, CPython uses SipHash-1-3 seeded with a fresh 128-bit random key per process (sys.hash_info.algorithm == 'siphash13'), so colliding strings change on every restart.
Watch two limits of CPython's defence:
- Pinning
PYTHONHASHSEED: settingPYTHONHASHSEED=0in a production container disables per-process randomisation, allowing attackers to reuse pre-computed colliding strings across restarts. - Integer keys are NOT randomised: as shown in the output above (
hash(42) == hash(2 * m + 42) == 42), CPython hashes integers deterministically modulosys.hash_info.modulus(2^61 - 1on 64-bit builds). SipHash does not randomiseintkeys, so untrusted user-supplied integers can still be crafted to collide across processes unless you cap key counts, convert/mix them with a keyed hash, or switch data structures.
When not to use a hash table under adversarial load: when keys are controlled by untrusted callers and deterministic collisions could stall your service—or when you require strict O(log n) worst-case time per operation—use a comparison-based balanced search tree instead (see Binary Search Trees). And if a class represents a mutable entity identified by object identity rather than field values, leave both __eq__ and __hash__ inherited from object.
04. Check your understanding
05. Apply it
Extend ConstantHashKey in a local script to compare eq_calls for n = 100, 200, and 400 inserts against 200 distinct GoodPoint(i, i) keys (verifying len == n for each). Confirm that doubling n on ConstantHashKey multiplies __eq__ calls by roughly 4x while GoodPoint stays near 0 collisions.
Next, combine dict with doubly linked nodes to build an O(1) LRU cache in Linked Lists, or compare hash tables with prefix trees in Tries & String Matching.
06. Review prompt
Without looking back:
- Why does defining
__eq__on a Python class automatically set__hash__ = None? - Why can
@dataclass(frozen=True)still raiseTypeErroronhash()if one of its fields is alist? - What does SipHash-1-3 protect in CPython, and what happens if you set
PYTHONHASHSEED=0or key adictwith untrusted integers?
References
- Python 3.12 docs - Data Model (__hash__ and __eq__)
- Python docs - Time complexity of operations on built-in types (current release)
- Python 3.12 docs - Design and History FAQ (Dictionaries in CPython)
- CPython 3.12 source - Objects/dictobject.c
- Python 3.12 docs - sys.hash_info
- Python 3.12 docs - PYTHONHASHSEED command-line option
- PEP 456 - Secure and interchangeable hash algorithm
- What's New In Python 3.11 - siphash13 becomes the default str/bytes hash (bpo-29410)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.