Why did your object vanish from a set after you changed it?
Question
A shopping cart is a set of Product objects. Two products are equal when they have the same sku. The code changes the sku of a product that is already in the cart, and then the cart can't find it.
What do the three print lines show, and why? Then change Product so this bug can't happen.
class Product: def __init__(self, sku, name): self.sku = sku self.name = name def __eq__(self, other): return isinstance(other, Product) and self.sku == other.sku def __hash__(self): return hash(self.sku) cart = {Product(101, "mug")} item = next(iter(cart)) item.sku = 202 print(item in cart) print(Product(101, "mug") in cart, Product(202, "mug") in cart) print(len(cart))
Show hints (3)
- "FILED UNDER"
A set files each item under its hash when you add it. It doesn't notice when the object changes later. Which hash did the mug have when it went in?
- "TWO DIFFERENT MISSES"
item in cartnow useshash(202), so it looks in a different place.Product(101, "mug")looks in the right place. But is it still equal to the stored mug? - "FREEZE THE KEY"
A key must not change while it is in a set or a dict. Make
Productimmutable with@dataclass(frozen=True), and let onlyskucount for==and the hash.
Show checked explanation
It prints False, then False False, then 1. The set stored the mug under hash(101). Changing sku changed its hash, but the set didn't move it. So every search misses, though the mug is still inside. Equal objects need equal hashes, and the hash of a key must not change. Make the key fields immutable.
from dataclasses import dataclass, field @dataclass(frozen=True) class Product: sku: int name: str = field(compare=False) # not part of == or the hash cart = {Product(101, "mug")} item = next(iter(cart)) try: item.sku = 202 except AttributeError as error: print(type(error).__name__) print(Product(101, "cup") in cart, len(cart))
FrozenInstanceError True 1
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
A set is a hash table, like a dict without values. cart = {Product(101, "mug")} calls hash(101) and stores the mug in the place that hash points to. Then item.sku = 202 changes the object, but nothing tells the set. The mug stays where hash(101) put it.
| search | where the set looks | result |
|---|---|---|
item in cart | the place for hash(202) | nothing there, False |
Product(101, "mug") in cart | the place for hash(101) | finds the mug, but its sku is now 202, so == fails: False |
Product(202, "mug") in cart | the place for hash(202) | nothing there, False |
The mug is still inside. len(cart) is 1, and a loop over the cart shows it. But no search reaches it, and cart.remove(item) raises KeyError.
The Python docs give the rule: objects that compare equal must have the same hash. A set or a dict also needs the hash of a stored key to stay the same. So a field used by __eq__ and __hash__ must not change while the object is a key.
@dataclass(frozen=True) makes the object read-only. Assigning to a field raises FrozenInstanceError, which is a kind of AttributeError. The dataclass writes __eq__ and __hash__ for you from the fields. field(compare=False) leaves name out of both. So products with the same sku are equal even when the names differ, and Product(101, "cup") in cart is True.
If you keep a mutable class, take the object out before you change it, then add it back:
cart.remove(item) item.sku = 202 cart.add(item)
Now the mug is stored under hash(202), and item in cart is True.
Common mistakes
- Defining
__eq__and forgetting__hash__. Python then sets__hash__toNone, and{Product(101, "mug")}raisesTypeError: unhashable type: 'Product'. - Silencing that error with
__hash__ = object.__hash__. The hash then comes from the object's identity, so two equal products get different hashes. A set keeps both, andlenis 2 instead of 1. - Hashing by adding fields:
return hash(self.store + self.sku). It is legal, but store 1 with sku 2 and store 2 with sku 1 always collide. Hash a tuple instead:hash((self.store, self.sku)). - Hashing a field that changes, like
price. Each price change hides the object again. Only hash fields that stay fixed while the object is in a set or a dict.
Follow-up questions
- "
d = {1: "a", 1.0: "b", True: "c"}. How many keys doesdhave?" One.1 == 1.0 == True, and Python gives equal numbers equal hashes, so all three are the same key. The dict keeps the first key object and takes the last value:dis{1: 'c'}. - "Why can't you use a list as a dict key?" A list can change, so
listsets__hash__toNone, andhash([1, 2])raisesTypeError. If a list key could change, you would get this exact bug. Use a tuple, such as(store, sku), or a frozen dataclass.
What a strong answer covers
Predicts all three results and explains each with the hash the set used. States the rule: equal objects have equal hashes, and a key's hash must not change. Fixes it with a frozen dataclass, and knows that __eq__ without __hash__ makes a class unhashable.
Open in interactive practice deck →