Code

Counting Stock

A shop doesn't keep ten copies of "rope" in a list. It keeps one line that says "rope: 10". In Python, that's a dict that maps each thing to how many you have:

stock = {}
stock["rope"] = stock.get("rope", 0) + 3   # add 3
stock["rope"] = stock.get("rope", 0) + 2   # add 2 more
print(stock)                               # {'rope': 5}
del stock["rope"]                          # gone completely

Objects as keys

The keys can be your own objects, if they are hashable. A frozen dataclass is perfect: two equal objects have the same hash, so they land on the same key.

@dataclass(frozen=True)
class Gem:
    name: str
    value: int

stock = {Gem("Opal", 5): 1}
print(stock[Gem("Opal", 5)])   # 1  (an equal Gem finds it)

This lesson builds the heart of the next boss, so take your time!

Assignment

  1. Make Gem a frozen dataclass with the fields name: str and value: int.
  2. Shelf.__init__ starts an empty dict called self._stock.
  3. count(gem) returns how many of gem you have, or 0.
  4. add(gem, qty=1): if qty is 0 or less, raise ValueError. Otherwise add qty to the count.
  5. remove(gem, qty=1): if you have fewer than qty, raise ValueError. Otherwise take qty away. When the count reaches 0, delete the key from self._stock.