Intermediate Python · Lesson 14 of 14

Project: an inventory manager

Combine dataclasses, custom exceptions, special methods, generators, a decorator and type hints in a small inventory program for a shop.

About 25 minutes · code runs in your browser, nothing to install

Time to put the course together. You will build a small inventory manager for a corner shop: it stores items, sells them, refuses impossible sales, warns about low stock and prints reports from a CSV file. Each step below is a complete program, so you can run it on its own.

  • A dataclass Item with a computed value (Special methods and dataclasses).
  • Custom exceptions for clear errors (Exceptions in depth).
  • An Inventory class with len(), in and for support, plus a generator for low stock.
  • A logging decorator (Decorators) and type hints throughout.
  • Reports with Counter, defaultdict, comprehensions and sorted with a key.

Step 1: the item and the errors

OutOfStock inherits from InventoryError, so callers can catch either the specific problem or every inventory problem at once.

Pythoneditable
from dataclasses import dataclass

class InventoryError(Exception):
    pass

class OutOfStock(InventoryError):
    pass

@dataclass
class Item:
    sku: str
    name: str
    category: str
    price: float
    qty: int = 0

    @property
    def value(self) -> float:
        return round(self.price * self.qty, 2)

lamp = Item("L-01", "Desk lamp", "home", 24.5, 4)
print(lamp)
print("Stock value:", lamp.value)
print(issubclass(OutOfStock, InventoryError))
Output
Item(sku='L-01', name='Desk lamp', category='home', price=24.5, qty=4)
Stock value: 98.0
True

Step 2: the inventory

The inventory keeps items in a dictionary keyed by their code (SKU, stock keeping unit). Special methods make it feel like a built-in collection, __iter__ is a generator that yields items sorted by name (yield from hands out every item of another iterable in turn), and @logged prints every change.

Pythoneditable
from dataclasses import dataclass

class InventoryError(Exception):
    pass

class OutOfStock(InventoryError):
    pass

@dataclass
class Item:
    sku: str
    name: str
    category: str
    price: float
    qty: int = 0

    @property
    def value(self) -> float:
        return round(self.price * self.qty, 2)

from collections.abc import Iterator
from functools import wraps

def logged(func):
    @wraps(func)
    def wrapper(self, *args):
        result = func(self, *args)
        print(f"[{func.__name__}] {', '.join(str(a) for a in args)}")
        return result
    return wrapper

class Inventory:
    def __init__(self) -> None:
        self.items: dict[str, Item] = {}

    def __len__(self) -> int:
        return len(self.items)

    def __contains__(self, sku: str) -> bool:
        return sku in self.items

    def __iter__(self) -> Iterator[Item]:
        yield from sorted(self.items.values(), key=lambda i: i.name)

    @logged
    def add(self, item: Item) -> None:
        if item.sku in self.items:
            raise InventoryError(f"{item.sku} already exists")
        self.items[item.sku] = item

    @logged
    def sell(self, sku: str, qty: int) -> float:
        if sku not in self.items:
            raise InventoryError(f"unknown item {sku}")
        item = self.items[sku]
        if qty > item.qty:
            raise OutOfStock(f"only {item.qty} x {item.name} left")
        item.qty -= qty
        return round(item.price * qty, 2)

    def low_stock(self, limit: int = 3) -> Iterator[Item]:
        for item in self:
            if item.qty <= limit:
                yield item

shop = Inventory()
shop.add(Item("L-01", "Desk lamp", "home", 24.5, 4))
shop.add(Item("T-07", "Green tea", "food", 3.8, 12))
shop.add(Item("M-02", "Mug", "home", 6.0, 2))

print(len(shop), "items;", "T-07" in shop)
print("Paid:", shop.sell("T-07", 3))

for sku, qty in [("L-01", 9), ("X-99", 1)]:
    try:
        shop.sell(sku, qty)
    except OutOfStock as e:
        print("Out of stock:", e)
    except InventoryError as e:
        print("Inventory error:", e)

print("Low stock:", [i.name for i in shop.low_stock()])
Output
[add] Item(sku='L-01', name='Desk lamp', category='home', price=24.5, qty=4)
[add] Item(sku='T-07', name='Green tea', category='food', price=3.8, qty=12)
[add] Item(sku='M-02', name='Mug', category='home', price=6.0, qty=2)
3 items; True
[sell] T-07, 3
Paid: 11.4
Out of stock: only 4 x Desk lamp left
Inventory error: unknown item X-99
Low stock: ['Mug']

The failed sales print no [sell] line, because the decorator only logs after the function succeeds.

Tip: Catch the most specific exception first. If except InventoryError came first, it would also catch every OutOfStock.

Step 3: loading a file and reporting

Real stock lists live in files. This step reads a CSV file with the csv module, turns each row into an Item and prints three reports. Only the parts this step needs are kept.

Pythoneditable
from dataclasses import dataclass

class InventoryError(Exception):
    pass

class OutOfStock(InventoryError):
    pass

@dataclass
class Item:
    sku: str
    name: str
    category: str
    price: float
    qty: int = 0

    @property
    def value(self) -> float:
        return round(self.price * self.qty, 2)

import csv
from collections import Counter, defaultdict

def load(path: str) -> list[Item]:
    with open(path, newline="", encoding="utf-8") as f:
        return [Item(r["sku"], r["name"], r["category"], float(r["price"]), int(r["qty"]))
                for r in csv.DictReader(f)]

items = load("stock.csv")
print(f"Loaded {len(items)} items")

per_category = Counter(i.category for i in items)
print("Items per category:", sorted(per_category.items()))

value_by_category: defaultdict[str, float] = defaultdict(float)
for i in items:
    value_by_category[i.category] += i.value
for cat, total in sorted(value_by_category.items()):
    print(f"  {cat:<6}{total:>8.2f}")

top = sorted(items, key=lambda i: i.value, reverse=True)[:2]
print("Most valuable stock:", [(i.name, i.value) for i in top])
Output
Loaded 5 items
Items per category: [('food', 2), ('home', 2), ('office', 1)]
  food    108.60
  home    110.00
  office   42.00
Most valuable stock: [('Desk lamp', 98.0), ('Rice 1kg', 63.0)]

Ideas to go further

  • Add a restock(sku, qty) method with the @logged decorator.
  • Save the inventory back to a CSV file with csv.DictWriter.
  • Keep a sales history list and report the best-selling item with Counter.
  • Split the code into modules: models.py, inventory.py and main.py.

✎ Exercise

Write restock_list(items, minimum=5) that returns a dictionary mapping the name of every item with fewer than minimum units to how many units are needed to reach minimum. Use a dictionary comprehension.

Hint: {i.name: minimum - i.qty for i in items if i.qty < minimum}

Your codewrite your answer, then Run
from dataclasses import dataclass

class InventoryError(Exception):
    pass

class OutOfStock(InventoryError):
    pass

@dataclass
class Item:
    sku: str
    name: str
    category: str
    price: float
    qty: int = 0

    @property
    def value(self) -> float:
        return round(self.price * self.qty, 2)

def restock_list(items: list[Item], minimum: int = 5) -> dict[str, int]:
    # your code here
    return {}

stock = [Item("L-01", "Desk lamp", "home", 24.5, 4), Item("T-07", "Green tea", "food", 3.8, 12),
         Item("M-02", "Mug", "home", 6.0, 2)]
print(restock_list(stock))
print(restock_list(stock, minimum=15))

Expected output:

{'Desk lamp': 1, 'Mug': 3}
{'Desk lamp': 11, 'Green tea': 3, 'Mug': 13}
Show a solution
Solutioneditable
from dataclasses import dataclass

class InventoryError(Exception):
    pass

class OutOfStock(InventoryError):
    pass

@dataclass
class Item:
    sku: str
    name: str
    category: str
    price: float
    qty: int = 0

    @property
    def value(self) -> float:
        return round(self.price * self.qty, 2)

def restock_list(items: list[Item], minimum: int = 5) -> dict[str, int]:
    return {i.name: minimum - i.qty for i in items if i.qty < minimum}

stock = [Item("L-01", "Desk lamp", "home", 24.5, 4), Item("T-07", "Green tea", "food", 3.8, 12),
         Item("M-02", "Mug", "home", 6.0, 2)]
print(restock_list(stock))
print(restock_list(stock, minimum=15))
Output
{'Desk lamp': 1, 'Mug': 3}
{'Desk lamp': 11, 'Green tea': 3, 'Mug': 13}

Check yourself

1. Why does OutOfStock inherit from InventoryError?

2. Which special method makes "T-07" in shop work?

3. What does yield from sorted(...) do inside __iter__?

Spotted a mistake on this page? Tell us