Show contents
Chapter 5 of 6 · 30 min
Final project: stock management for a shop
By the end of this chapter, you'll be able to
- Model a problem with a dataclass and a class that applies the rules
- Refuse invalid operations with explicit exceptions
- Save and reload the application's complete state as JSON
- Check the application with tests on normal and invalid cases
Step 1: rules and design
The business rules:
- each product has a unique code, a name, a positive price and a quantity in stock;
- you can't sell more than the quantity available, nor an unknown product;
- the shop tracks its revenue, that is, the total of its sales;
- a product must be reordered when there are 5 or fewer left;
- the whole state can be saved and reloaded.
Two classes are enough:
Product: a dataclass, a simple bundle of values;Stock: the products, stored in a dictionary{code: product}, and all the rules. The rest of the program never touches the products directly.
The program catches the error and displays it. The stock hasn't moved.
Text description of the animation
- The program asks for a sale: it never changes a product itself.
- The stock finds the product thanks to its code.
- The quantity requested is available.
- The quantity goes down and the revenue goes up, always together.
- The method returns the amount of the sale.
- For 8 pens when there are 6 left, the sale is refused before any change.
- The program catches the error and displays it. The stock hasn't moved.
Step 2: the program
import json
from dataclasses import dataclass, asdict
@dataclass
class Product:
code: str
name: str
price: float
quantity: int = 0
class Stock:
ALERT_THRESHOLD = 5
def __init__(self):
self._products = {}
self.revenue = 0.0
def add(self, product):
if product.code in self._products:
raise ValueError(f"the code {product.code} already exists")
if product.price <= 0 or product.quantity < 0:
raise ValueError(f"invalid data for {product.name}")
self._products[product.code] = product
def _find(self, code):
try:
return self._products[code]
except KeyError:
raise ValueError(f"unknown product: {code}") from None
def sell(self, code, quantity):
product = self._find(code)
if quantity <= 0:
raise ValueError("the quantity sold must be positive")
if quantity > product.quantity:
raise ValueError(f"not enough stock for {product.name} ({product.quantity} left)")
product.quantity -= quantity
amount = round(quantity * product.price, 2)
self.revenue = round(self.revenue + amount, 2)
return amount
def restock(self, code, quantity):
if quantity <= 0:
raise ValueError("the quantity received must be positive")
self._find(code).quantity += quantity
def alerts(self):
return sorted(p.name for p in self._products.values() if p.quantity <= self.ALERT_THRESHOLD)
def value(self):
return round(sum(p.price * p.quantity for p in self._products.values()), 2)
def save(self, path):
data = {"revenue": self.revenue,
"products": [asdict(p) for p in self._products.values()]}
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
@classmethod
def load(cls, path):
stock = cls()
with open(path, encoding="utf-8") as f:
data = json.load(f)
for p in data["products"]:
stock.add(Product(**p))
stock.revenue = data["revenue"]
return stock
shop = Stock()
shop.add(Product("SOA-01", "Shea butter soap", 1.5, 40))
shop.add(Product("EXB-02", "Exercise book, 96 pages", 2.0, 12))
shop.add(Product("PEN-03", "Blue pen", 0.5, 6))
for code, quantity in [("EXB-02", 10), ("PEN-03", 8), ("SOA-01", 3), ("ERA-04", 1)]:
try:
print(f"Sale {code} x{quantity}: {shop.sell(code, quantity)}")
except ValueError as error:
print("Refused:", error)
print("To reorder:", shop.alerts())
shop.restock("EXB-02", 20)
print("Stock value:", shop.value(), "; revenue:", shop.revenue)
shop.save("shop.json")
copy = Stock.load("shop.json")
print("Reloaded:", copy.value() == shop.value(), copy.alerts())
Sale EXB-02 x10: 20.0
Refused: not enough stock for Blue pen (6 left)
Sale SOA-01 x3: 4.5
Refused: unknown product: ERA-04
To reorder: ['Exercise book, 96 pages']
Stock value: 102.5 ; revenue: 24.5
Reloaded: True []
The choices that matter:
- A single way in.
_productsstarts with_: it's only handled through the methods, which apply all the rules. - Check before changing.
sellchecks everything, then changes the quantity and the revenue. A refused sale therefore leaves no half-done change behind. raise ValueError(...) from Nonereplaces the technicalKeyErrorwith an understandable message, without showing the original error.ALERT_THRESHOLDis a class attribute, a constant shared by all stocks.asdict(p)turns a dataclass into a dictionary, ready for JSON.Product(**p)does the reverse:**passes each key of the dictionary as a named argument.@classmethoddefines a method called on the class itself (Stock.load(...)), handy for building an object another way. Its first parameter,cls, is the class.
Step 3: the tests
Each test starts from a brand-new stock, built by a small function: that way, no test depends on what another one changed. The third test checks the most important rule: a refused sale changes nothing.
from dataclasses import dataclass
@dataclass
class Product:
code: str
name: str
price: float
quantity: int = 0
class Stock:
def __init__(self):
self._products = {}
self.revenue = 0.0
def add(self, product):
self._products[product.code] = product
def sell(self, code, quantity):
product = self._products[code]
if quantity > product.quantity:
raise ValueError("not enough stock")
product.quantity -= quantity
self.revenue = round(self.revenue + quantity * product.price, 2)
def new_stock():
s = Stock()
s.add(Product("A", "Rice 1 kg", 1.2, 10))
return s
def test_sale_reduces_stock():
s = new_stock()
s.sell("A", 3)
assert s._products["A"].quantity == 7
def test_sale_increases_revenue():
s = new_stock()
s.sell("A", 2)
assert s.revenue == 2.4
def test_oversized_sale_refused_without_effect():
s = new_stock()
try:
s.sell("A", 50)
raise AssertionError("the sale should have been refused")
except ValueError:
pass
assert s._products["A"].quantity == 10 and s.revenue == 0
for test in (test_sale_reduces_stock, test_sale_increases_revenue, test_oversized_sale_refused_without_effect):
test()
print("OK", test.__name__)
OK test_sale_reduces_stock
OK test_sale_increases_revenue
OK test_oversized_sale_refused_without_effect
To keep the example short, this simplified version of Stock only contains what's tested. In your project, keep the full version from step 2, and test the other rules too: unknown product, restocking, alerts, saving then reloading.
The tests read _products directly here. That's acceptable in a test, which is allowed to look inside in order to check. The rest of the program doesn't touch it.
Your turn
Project: add a sales historyPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: the end-of-season discount
Add to Stock a method apply_discount(percentage, threshold) that lowers by percentage % the price of every product whose quantity is above threshold, rounded to the cent. It returns the sorted list of the names of the products concerned, and raises a ValueError if the percentage isn't strictly between 0 and 100.
Hint 1
self._products.values() and change p.price for each product concerned.Hint 2
1 - 20 / 100, that is 0.8.Show the solution and common mistakes
from dataclasses import dataclass
@dataclass
class Product:
code: str
name: str
price: float
quantity: int = 0
class Stock:
def __init__(self):
self._products = {}
def add(self, product):
self._products[product.code] = product
def apply_discount(self, percentage, threshold):
if not 0 < percentage < 100:
raise ValueError("discount between 1 and 99 %")
concerned = []
for p in self._products.values():
if p.quantity > threshold:
p.price = round(p.price * (1 - percentage / 100), 2)
concerned.append(p.name)
return sorted(concerned)
s = Stock()
s.add(Product("SOA-01", "Shea butter soap", 1.5, 40))
s.add(Product("EXB-02", "Exercise book, 96 pages", 2.0, 12))
s.add(Product("PEN-03", "Blue pen", 0.5, 6))
print(s.apply_discount(20, 10))
print([p.price for p in s._products.values()])
try:
s.apply_discount(150, 0)
except ValueError as error:
print("Refused:", error)
['Exercise book, 96 pages', 'Shea butter soap']
[1.2, 1.6, 0.5]
Refused: discount between 1 and 99 %
Common mistakes:
- Checking the percentage after starting to change the prices: some products would already be discounted when the error happens.
- Forgetting
round(..., 2): a price like1.6000000000000003ends up appearing on the labels.
Summary
- 1A dataclass carries the data, a class applies all the business rules.
- 2Check everything before changing anything: a refused operation leaves no trace.
- 3asdict and Product(**d) go back and forth between objects and JSON.
- 4Each test starts from a fresh state and also checks what must be refused.
- 5Copying a list doesn't copy the objects it contains.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.