__hash__: objects in sets and as dict keys
🌍 In real life. At a cloakroom you hand in your coat and get a ticket with a hook number. To find your coat, the attendant goes straight to that hook and then checks it really is yours, instead of searching every hook. That only works if the same coat always gets the same number.
Sets and dicts work the same way. The idea in one sentence: a set or dict first asks hash(x) for a number that says where to look, and only then uses == on the few items found there, so objects that are equal must have equal hashes.
Its words:
- hash: a whole number worked out from an object;
hash(x)callsx.__hash__() - hashable: has a hash that never changes, so it can go in a set or be a dict key (numbers, strings, and tuples of hashable things; lists are not)
- the rule: if
a == b, thenhash(a) == hash(b)(the reverse needn't hold) - collision: two different objects with the same hash; legal, but they then have to be told apart with
==
What {a, b} does, step by step:
- ask
a.__hash__()and putawhere that number points - ask
b.__hash__(); if the numbers differ,bis a different item: done, no==needed - if they match, check
a == b:Truemeansbis a duplicate and isn't added;Falsemeans a collision, and both stay
Here Tag uses the length of its name as its hash (a deliberately weak one, so a collision is easy to see): cat and dog share 3.
The trap: __eq__ alone makes objects unhashable. Before you write __eq__, every object is equal only to itself, and the default hash comes from its identity, which agrees with that. Once you write __eq__, two different objects can be equal, and the identity hash would put them in different places. So Python sets __hash__ to None, and the object can't go in a set at all:
The fix: write __hash__ from exactly the fields __eq__ compares. The usual way is to hash a tuple of them, hash((self.x, self.y)), which mixes all the fields into one number. Equal points then have equal tuples, so equal hashes, and the rule holds:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y)) # the same fields __eq__ compares
visited = {Point(0, 0), Point(1, 2), Point(0, 0)}
print(len(visited))
print(Point(1, 2) in visited)
owners = {Point(0, 0): "Ana"}
print(owners[Point(0, 0)])What it costs, by counting. With a good hash, almost every slot holds one item, so x in s costs about one hash and one ==: O(1), however big the set. With a bad hash the set still works, but it slows down. Tag's length hash puts every 5-letter word in the same place, so for 1,000 such words, each lookup compares against up to 1,000 of them: O(n), like searching a list. And return 0 (legal!) makes every lookup compare against everything. Chapter 35 shows the buckets inside a set.
Mistakes and edge cases.
__eq__without__hash__: a TypeError that says "unhashable type"; add a__hash__from the same fields- a hash that disagrees with
__eq__: if__eq__ignores upper and lower case but__hash__doesn't, equal objects land in different places and a set keeps duplicates - changing a field after the object is in a set: the set looks in the place for the new hash and can't find it; hash only fields that never change (Chapter 25's
frozen=Truedataclasses do this for you) - returning something that isn't a whole number:
TypeError: __hash__ method should return an integer
Why must equal objects have equal hashes? A set looks only in the slot its hash points to. If two equal points had different hashes, Point(1, 2) in s would look in the wrong slot and say False, even though an equal point is right there. The rule "equal objects, equal hashes" is what makes the fast lookup correct, not just fast.
Quiz
What does this print?
class Tag: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name try: s = {Tag("a")} except TypeError as e: print(e)What does this print?
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __hash__(self): return hash((self.x, self.y)) print(len({Point(1, 2), Point(1, 2), Point(2, 1)}))No eq and no hash. What does this print?
class Coin: def __init__(self, value): self.value = value print(len({Coin(5), Coin(5)}))Which rule must hash follow?
- If a == b, then hash(a) == hash(b)
- If hash(a) == hash(b), then a == b
- Every object needs a different hash
The box changes after it goes into the set. What does this print?
class Box: def __init__(self, n): self.n = n def __eq__(self, other): return self.n == other.n def __hash__(self): return hash(self.n) b = Box(1) s = {b} b.n = 2 print(Box(2) in s, b in s)Which line stops this program with an error?
class P: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x seen = {P(1)}
Coding tasks
Pointhas an__eq__but can't go in a set. Add a__hash__that agrees with it, so equal points count once in a set and work as dict keys.Wordcompares its text without caring about upper and lower case, but its__hash__disagrees, so a set keepsWord("Hi")andWord("hi")as two. Fix__hash__so the rule holds.