These exercises practice what the Module 14 reading explained. They aren’t graded.
Work in the folder m14 inside py101, as in the reading, and run tests with
python -m pytest, using your environment’s Python, as in Module 13. Write your answer or your
prediction first, then run the code to check it. The answers are in the collapsed blocks; open
one only after you have an answer of your own.
Worked example: a class, its invariant, and its tests¶
A parking lot has a fixed number of spaces and knows which cars are in it, by their license
plates. Before writing any code, state the invariant: the capacity is more than 0, and the lot
holds from 0 up to capacity cars, each plate once. A set holds the plates, because a set can’t
hold one plate twice, which keeps part of the invariant without a check. Save this as
parking.py:
"""A parking lot that knows which cars are in it."""
class ParkingLot:
"""A parking lot with a fixed number of spaces.
Invariant: capacity > 0, and the lot holds from 0 to capacity cars, each plate once.
"""
def __init__(self, capacity):
if not capacity > 0:
raise ValueError(f"capacity must be more than 0, not {capacity}")
self.capacity = capacity
self.plates = set()
def free(self):
"""Return the number of free spaces."""
return self.capacity - len(self.plates)
def park(self, plate):
"""Park the car with this plate."""
if plate in self.plates:
raise ValueError(f"{plate} is already parked here")
if self.free() == 0:
raise ValueError("the lot is full")
self.plates.add(plate)
def leave(self, plate):
"""Let the car with this plate leave."""
if plate not in self.plates:
raise ValueError(f"{plate} isn't parked here")
self.plates.remove(plate)Every method that changes the lot checks first and changes after, so a refused call leaves the
lot as it was. The tests check exactly that: after each error, the lot still holds what it held.
A fixture gives each test a lot with two spaces, one of them taken. Save this as
test_parking.py:
import pytest
from parking import ParkingLot
@pytest.fixture
def lot():
"""Return a lot with two spaces, one of them taken."""
lot = ParkingLot(2)
lot.park("KA-1234")
return lot
def test_a_new_lot_is_empty():
assert ParkingLot(3).free() == 3
@pytest.mark.parametrize("capacity", [0, -1])
def test_a_lot_needs_spaces(capacity):
with pytest.raises(ValueError, match="capacity"):
ParkingLot(capacity)
def test_park_and_leave(lot):
lot.park("B-77")
assert lot.free() == 0
lot.leave("KA-1234")
assert lot.free() == 1
def test_a_full_lot_refuses_a_car_and_stays_full(lot):
lot.park("B-77")
with pytest.raises(ValueError, match="full"):
lot.park("M-5")
assert lot.plates == {"KA-1234", "B-77"}
def test_a_car_cannot_park_twice(lot):
with pytest.raises(ValueError, match="already"):
lot.park("KA-1234")
assert lot.free() == 1
def test_a_car_that_is_not_there_cannot_leave(lot):
with pytest.raises(ValueError, match="isn't parked"):
lot.leave("B-77")
assert lot.free() == 1....... [100%]
7 passed in 0.01sExercises¶
Exercise 14.1 (LO-14.1, ★, about 10 minutes)¶
Predict both lines this prints, then run it to check.
class Die:
rolls = 0
def __init__(self, sides):
self.sides = sides
self.history = []
def roll(self, value):
Die.rolls += 1
self.history.append(value)
return len(self.history)
red = Die(6)
blue = Die(20)
red.roll(4)
blue.roll(17)
print(red.roll(2), Die.rolls, blue.rolls, len(blue.history))
blue.rolls = 100
print(Die.rolls, red.rolls, blue.rolls)Hint
rolls is assigned in the class body, so it belongs to the class. Python looks an attribute up on the instance first, then on its class. Assigning to blue.rolls creates an attribute on blue.
Answer
2 3 3 1
3 3 100Die.rolls counts the rolls of every die, 3, and blue.rolls finds it on the class. red.roll(2) returns 2, the length of red’s own history. blue.rolls = 100 creates an instance attribute that hides the class attribute for blue alone, so Die.rolls and red.rolls are still 3.
Exercise 14.2 (LO-14.2, LO-13.1, ★★, about 20 minutes)¶
This countdown timer keeps the invariant length > 0, and 0 <= remaining <= length. Finish
tick and reset, then write tests in test_countdown.py: typical use, the edges, and each
error, checking that a refused call changes nothing.
"""A countdown timer's arithmetic."""
class Countdown:
"""Seconds counting down to zero.
Invariant: length > 0, and 0 <= remaining <= length.
"""
def __init__(self, length):
if not length > 0:
raise ValueError(f"length must be more than 0, not {length}")
self.length = length
self.remaining = length
def is_done(self):
"""Return True once no seconds remain."""
return self.remaining == 0
def tick(self, seconds=1):
"""Count down by seconds, stopping at 0, and return the seconds remaining."""
# Refuse a negative number of seconds with ValueError, and stop at 0.
def reset(self):
"""Start again from length."""
# Write this.Hint
max(self.remaining - seconds, 0) stops at 0. Check seconds before changing anything.
Answer
def tick(self, seconds=1):
"""Count down by seconds, stopping at 0, and return the seconds remaining."""
if not seconds >= 0:
raise ValueError(f"seconds can't be negative: {seconds}")
self.remaining = max(self.remaining - seconds, 0)
return self.remaining
def reset(self):
"""Start again from length."""
self.remaining = self.lengthimport pytest
from countdown import Countdown
def test_a_new_countdown_has_its_whole_length():
timer = Countdown(60)
assert (timer.remaining, timer.is_done()) == (60, False)
@pytest.mark.parametrize("length", [0, -5])
def test_a_countdown_needs_a_length(length):
with pytest.raises(ValueError, match="length"):
Countdown(length)
def test_tick_counts_down():
timer = Countdown(60)
assert timer.tick() == 59
assert timer.tick(9) == 50
def test_tick_stops_at_zero():
timer = Countdown(10)
assert timer.tick(25) == 0
assert timer.is_done()
def test_a_negative_tick_is_refused_and_changes_nothing():
timer = Countdown(10)
with pytest.raises(ValueError, match="negative"):
timer.tick(-1)
assert timer.remaining == 10
def test_reset_starts_again():
timer = Countdown(10)
timer.tick(4)
timer.reset()
assert timer.remaining == 107 passed in 0.01stick(25) on a 10-second timer is the edge that tests the “stopping at 0” promise; without max, remaining would become -15 and break the invariant. reset needs no check: length was checked in __init__, and setting remaining to it keeps the invariant.
Exercise 14.3 (LO-14.3, ★★, about 15 minutes)¶
Add __repr__ and __eq__ to this class, so that Money(150, "USD") shows as
Money(cents=150, currency='USD'), and two amounts are equal when both their cents and their
currencies are. Then predict what each line gives:
class Money:
"""An amount of money, in cents, in one currency."""
def __init__(self, cents, currency):
self.cents = cents
self.currency = currencyMoney(150, "USD") == Money(150, "EUR")
Money(150, "USD") == 150
{Money(1, "USD")}Answer
def __repr__(self):
return f"Money(cents={self.cents!r}, currency={self.currency!r})"
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.cents, self.currency) == (other.cents, other.currency)The first line is False: the currencies differ. The second is False: __eq__ returns NotImplemented, the int doesn’t know about Money either, and Python falls back to identity. The third raises TypeError: unhashable type: 'Money', because defining __eq__ removes the default hash. @dataclass(frozen=True) with the fields cents: int and currency: str gives the same __repr__ and __eq__, and a hash, so amounts could go in a set.
Exercise 14.4 (LO-14.3, ★★, about 15 minutes)¶
Rewrite this class as a dataclass, with type hints, that behaves the same way. Then predict what
the three print calls show.
class Book:
"""A book on a reading list."""
def __init__(self, title, author, year, tags=None):
self.title = title
self.author = author
self.year = year
if tags is None:
tags = []
self.tags = tags
def __repr__(self):
return (f"Book(title={self.title!r}, author={self.author!r}, year={self.year!r}, "
f"tags={self.tags!r})")
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title, self.author, self.year, self.tags) == (
other.title, other.author, other.year, other.tags)first = Book("The Quiet Harbor", "A. Writer", 2019)
second = Book("Maps of Rain", "B. Author", 2024, ["weather"])
first.tags.append("sea")
print(first)
print(second.tags, Book("X", "Y", 2000).tags)
print(first == Book("The Quiet Harbor", "A. Writer", 2019, ["sea"]))Hint
tags=None, then a new list, is the hand-written way to give each book its own list. A dataclass does the same with field(default_factory=list).
Answer
from dataclasses import dataclass, field
@dataclass
class Book:
"""A book on a reading list."""
title: str
author: str
year: int
tags: list[str] = field(default_factory=list)Book(title='The Quiet Harbor', author='A. Writer', year=2019, tags=['sea'])
['weather'] []
TrueEach book gets its own list, so appending to first.tags leaves the new Book("X", "Y", 2000) with []. This dataclass isn’t frozen, because its tags change; frozen=True wouldn’t help anyway, since a list field can’t be hashed.
Exercise 14.5 (LO-14.4, ★★, about 15 minutes)¶
Save this as cart.py. Before running it, find the three places where a value doesn’t match its
type hint. Then say which of them Python reports when the program runs, and why the others go
unnoticed.
from dataclasses import dataclass
@dataclass
class Item:
name: str
price_cents: int
quantity: int = 1
def total_cents(items: list[Item]) -> int:
total = 0
for item in items:
total += item.price_cents * item.quantity
return total
def find(items: list[Item], name: str) -> Item | None:
for item in items:
if item.name == name:
return item
return None
def describe(item: Item) -> str:
return item.name + ": " + item.price_cents
cart = [Item("tea", 450), Item("milk", "129", 2)]
print(find(cart, "tea").price_cents)
print(total_cents(cart))Answer
mypy, which Module 18 installs, reports all three without running anything:
cart.py:26: error: Unsupported operand types for + ("str" and "int") [operator]
cart.py:29: error: Argument 2 to "Item" has incompatible type "str"; expected "int" [arg-type]
cart.py:30: error: Item "None" of "Item | None" has no attribute "price_cents" [union-attr]
Found 3 errors in 1 file (checked 1 source file)Running it prints 450, then stops with TypeError: unsupported operand type(s) for +=: 'int' and 'str' inside total_cents: "129" * 2 is the string "129129", and adding it to an int fails, three lines away from the real mistake on line 29. The other two never run into trouble here: describe is never called, and find happens to find the tea, but find(cart, "coffee") returns None, and None.price_cents would crash.
Exercise 14.6 (LO-14.2, LO-13.3, ★★, about 15 minutes)¶
This class breaks its own invariant. Find the bug, capture it in a failing test, then fix it and run the test again.
"""The lowest and highest values seen so far."""
class Extremes:
"""The lowest and highest of the values seen since the last reset.
Invariant: lowest and highest are both None before the first value, and after it
lowest <= highest, and both are values that were seen.
"""
def __init__(self):
self.lowest = None
self.highest = None
def see(self, value):
"""Take one more value into account."""
if self.lowest is None:
self.lowest = value
self.highest = value
elif value < self.lowest:
self.lowest = value
elif value > self.highest:
self.highest = value
def reset(self):
"""Forget every value seen so far."""
self.lowest = 0
self.highest = 0Hint
After reset, which values has the object “seen”, according to its docstring? Try reset, then only positive values.
Answer
reset sets both to 0 instead of None, so after a reset, 0 counts as a value that was seen. Seeing 5 and 8 then leaves lowest at 0. This test captures it:
from extremes import Extremes
def test_after_reset_only_new_values_count():
extremes = Extremes()
extremes.see(-10)
extremes.reset()
extremes.see(5)
extremes.see(8)
assert (extremes.lowest, extremes.highest) == (5, 8)> assert (extremes.lowest, extremes.highest) == (5, 8)
E assert (0, 8) == (5, 8)The fix sets both to None in reset, as __init__ does, and the test passes. Writing self.__init__() in reset would work too, but calling __init__ yourself surprises readers; setting the two attributes says what reset means.