These exercises practice what the Module 15 reading explained. They aren’t graded.
Work in the folder m15 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 playlist by composition, with tests¶
A playlist holds songs in the order they play, and never holds one song twice. Is a playlist a
list? It is ordered like one, but a list also offers insert, extend, and +=, and each of
them could add a song twice. So a playlist holds a list, and offers only the operations that keep
its invariant: add, the total length, len, for, and +, which joins two playlists into a
new one. Each song is a frozen dataclass, as in Module 14, so two songs with the same title and
length are equal. Save this as playlist.py:
"""A playlist of songs, built by composition."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Song:
"""A song and its length, in seconds."""
title: str
seconds: int
class Playlist:
"""Songs in the order they play. Invariant: no song appears twice."""
def __init__(self):
self._songs = []
def add(self, song):
"""Add song at the end; it must not be in the playlist already."""
if song in self._songs:
raise ValueError(f"{song.title!r} is already in the playlist")
self._songs.append(song)
def seconds(self):
"""Return the playlist's total length, in seconds."""
return sum([song.seconds for song in self._songs])
def __len__(self):
return len(self._songs)
def __iter__(self):
return iter(self._songs)
def __add__(self, other):
if not isinstance(other, Playlist):
return NotImplemented
combined = Playlist()
for song in list(self) + list(other):
combined.add(song)
return combined__add__ builds the new playlist by calling add for each song, so joining two playlists that
share a song raises the same ValueError as adding a song twice: every way into a playlist goes
through one check. It returns NotImplemented for anything that isn’t a playlist, as the
reading’s Vector did. Using it:
from playlist import Playlist, Song
mix = Playlist()
mix.add(Song("Intro", 95))
mix.add(Song("Rain", 214))
longest = max(mix, key=lambda song: song.seconds)
print(len(mix), mix.seconds(), longest.title)
for song in mix:
print(song)
mix.add(Song("Rain", 214))2 309 Rain
Song(title='Intro', seconds=95)
Song(title='Rain', seconds=214)max and the for loop work because Playlist has __iter__, and len works because it has
__len__. The last line adds a song equal to one already there, and its traceback ends with:
ValueError: 'Rain' is already in the playlistThe tests check typical use, the edges, and both ways in, add and +. A helper function makes a
playlist from a list of songs. Save this as test_playlist.py:
import pytest
from playlist import Playlist, Song
INTRO = Song("Intro", 95)
RAIN = Song("Rain", 214)
CODA = Song("Coda", 180)
def make_playlist(songs):
"""Return a playlist of these songs, in this order."""
playlist = Playlist()
for song in songs:
playlist.add(song)
return playlist
def test_a_new_playlist_is_empty():
playlist = Playlist()
assert len(playlist) == 0
assert playlist.seconds() == 0
def test_songs_play_in_the_order_they_were_added():
playlist = make_playlist([RAIN, INTRO])
assert list(playlist) == [RAIN, INTRO]
assert playlist.seconds() == 309
def test_a_song_cannot_be_added_twice():
playlist = make_playlist([INTRO])
with pytest.raises(ValueError, match="Intro"):
playlist.add(Song("Intro", 95))
assert len(playlist) == 1
def test_adding_playlists_makes_a_new_one():
first = make_playlist([INTRO])
second = make_playlist([RAIN, CODA])
both = first + second
assert list(both) == [INTRO, RAIN, CODA]
assert (len(first), len(second)) == (1, 2)
def test_adding_playlists_keeps_the_invariant():
with pytest.raises(ValueError, match="Intro"):
make_playlist([INTRO]) + make_playlist([RAIN, INTRO])
def test_a_playlist_plus_a_list_is_a_type_error():
with pytest.raises(TypeError):
make_playlist([INTRO]) + [RAIN]...... [100%]
6 passed in 0.01sExercises¶
Exercise 15.1 (LO-15.1, ★, about 10 minutes)¶
Predict the four lines this prints, then run it to check.
class Shape:
sides = 0
def __init__(self, name):
self.name = name
def area(self):
return 0
def describe(self):
return f"{self.name}: {self.sides} sides, area {self.area()}"
class Rectangle(Shape):
sides = 4
def __init__(self, width, height):
super().__init__("rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
self.name = "square"
print(Shape("point").describe())
print(Rectangle(2, 3).describe())
print(Square(5).describe())
print(isinstance(Square(1), Rectangle), [cls.__name__ for cls in Square.__mro__])Hint
self.sides and self.area() are looked up on the object, starting from its own class. Square defines neither, so Python keeps going along the method resolution order.
Answer
point: 0 sides, area 0
rectangle: 4 sides, area 6
square: 4 sides, area 25
True ['Square', 'Rectangle', 'Shape', 'object']describe is defined only in Shape, but self.sides and self.area() find the subclass’s versions: Rectangle sets sides = 4 and overrides area, and Square inherits both from Rectangle. Square.__init__ passes its side to Rectangle.__init__ as both the width and the height, and Rectangle.__init__ sets the name to "rectangle" through Shape.__init__; Square.__init__ then replaces it with "square". A square is a rectangle here, so isinstance gives True.
Exercise 15.2 (LO-15.1, LO-13.1, ★★, about 15 minutes)¶
Inventory counts the items in stock. AuditedInventory is an inventory that also keeps a
history of every change it makes, as (action, item, count) tuples. Save this as inventory.py,
and finish remove:
"""An inventory, and a subclass that keeps a history of its changes."""
class Inventory:
"""Counts of items in stock. Invariant: every count is more than 0."""
def __init__(self):
self.counts = {}
def add(self, item, count=1):
"""Add count of item; count must be more than 0."""
if not count > 0:
raise ValueError(f"count must be more than 0, not {count}")
self.counts[item] = self.counts.get(item, 0) + count
def remove(self, item, count=1):
"""Remove count of item; there must be that many in stock."""
in_stock = self.counts.get(item, 0)
if not 0 < count <= in_stock:
raise ValueError(f"can't remove {count} {item}: {in_stock} in stock")
self.counts[item] -= count
if self.counts[item] == 0:
del self.counts[item]
def total(self):
"""Return the number of items in stock."""
return sum(self.counts.values())
class AuditedInventory(Inventory):
"""An inventory that records every change it makes."""
def __init__(self):
super().__init__()
self.history = []
def add(self, item, count=1):
super().add(item, count)
self.history.append(("add", item, count))
def remove(self, item, count=1):
... # Remove the items, then record the change.Then write test_inventory.py, with a fixture that gives each test an audited inventory holding 3
apples and 2 pears. Test that changes are recorded in order, that an audited inventory is an
Inventory, and that a refused add or remove changes neither the counts nor the history.
Before you run anything, answer two questions:
What would happen if
AuditedInventory.__init__didn’t callsuper().__init__()?Why does
addcallsuper().addbefore it appends to the history, and not after?
Hint
remove follows the same pattern as add. For the questions: which attribute does Inventory.__init__ create, and what does super().add do with a count of -1?
Answer
def remove(self, item, count=1):
super().remove(item, count)
self.history.append(("remove", item, count))import pytest
from inventory import AuditedInventory, Inventory
@pytest.fixture
def shelf():
"""Return an audited inventory with 3 apples and 2 pears."""
shelf = AuditedInventory()
shelf.add("apple", 3)
shelf.add("pear", 2)
return shelf
def test_changes_are_recorded_in_order(shelf):
shelf.remove("apple", 3)
assert shelf.history == [("add", "apple", 3), ("add", "pear", 2), ("remove", "apple", 3)]
assert shelf.counts == {"pear": 2}
assert shelf.total() == 2
def test_an_audited_inventory_is_an_inventory(shelf):
assert isinstance(shelf, Inventory)
@pytest.mark.parametrize("item, count", [("apple", 4), ("plum", 1), ("pear", 0)])
def test_a_refused_remove_changes_nothing(shelf, item, count):
with pytest.raises(ValueError):
shelf.remove(item, count)
assert shelf.counts == {"apple": 3, "pear": 2}
assert len(shelf.history) == 2
def test_a_refused_add_is_not_recorded(shelf):
with pytest.raises(ValueError, match="more than 0"):
shelf.add("apple", -1)
assert len(shelf.history) == 2...... [100%]
6 passed in 0.01sInventory.__init__createscounts. Without the call, the inventory never gets it, and the firstaddraisesAttributeError: 'AuditedInventory' object has no attribute 'counts'.super().addraises before it changes anything when it refuses a count, so the line after it never runs: the history records only the changes that happened. A method that appends first records a change that never happened. With the two lines ofremoveswapped, the three refused-remove tests fail, the first of them with:E AssertionError: assert 3 == 2 E + where 3 = len([('add', 'apple', 3), ('add', 'pear', 2), ('remove', 'apple', 4)])
AuditedInventory passes the reading’s test for inheritance: it keeps every promise that Inventory makes, and adds one of its own.
Exercise 15.3 (LO-15.2, ★★, about 15 minutes)¶
For each design, choose inheritance or composition, and give the reason in a sentence or two. The table at the end of the reading’s composition section lists the questions to ask.
A
Stack, whose items are added and removed only at the top. Alistcould hold the items.A
Robotthat runs on aBattery, and swaps it for a charged one when it runs low.A
Tram. AVehicleclass already has aname, acapacity, aboard(people)method that refuses passengers past the capacity, anddescribe(). A tram does all of that, and also runs on a numbered line.The
Squarefrom exercise 15.1, afterRectanglegains a methodset_width(width), which changes the width and leaves the height as it was.
Answer
Composition. A list offers
insert,remove,sort,pop(0), and+=, which reach the middle or the bottom of the stack, and a subclass would have to override every one of them. Exercise 15.6 builds this stack.Composition. A robot has a battery; it isn’t one. Holding the battery in an attribute also lets the robot swap it while it runs, which a base class can’t do.
Inheritance. A tram is a vehicle in every way a vehicle is used, so code that boards passengers or describes vehicles works with a tram unchanged.
Tramadds alineattribute, and extendsdescribewithsuper().Not inheritance. Code that calls
set_widthon a rectangle expects the height to stay as it was, and a square can’t keep that promise: ifset_widthchanges only the width, the square isn’t square any more, and if it changes both, the height didn’t stay. MakeSquarea class of its own, with aside. In exercise 15.1 the inheritance was fine, becauseRectanglemade no such promise. Whether a subclass works depends on what its base class promises, so adding a method to a base class can break a subclass that worked before.
Exercise 15.4 (LO-15.3, ★★, about 15 minutes)¶
Write
Duration, a length of time in whole minutes, induration.py.Duration(minutes)refuses a negative number withValueError. Give it__repr__, which showsDuration(45);__eq__and__lt__, with@functools.total_ordering; and__add__, which adds two durations. The comparisons and__add__returnNotImplementedfor anything that isn’t aDuration.Predict what each line of this prints, then run it:
from duration import Duration talks = [Duration(45), Duration(20), Duration(30)] print(sorted(talks), max(talks), Duration(20) <= Duration(30)) print(Duration(45) + Duration(20)) print(sum(talks))The last line fails. Explain why, then make the total work without changing
Duration.
Hint
sum(talks) computes 0 + talks[0], then adds each other item to the result. What does int do with + and a Duration, and what does Python try next? sum takes a second argument, start, the value it starts from, which is 0 unless you give another.
Answer
import functools
@functools.total_ordering
class Duration:
"""A length of time, in whole minutes."""
def __init__(self, minutes):
if not minutes >= 0:
raise ValueError(f"a duration can't be negative: {minutes}")
self.minutes = minutes
def __repr__(self):
return f"Duration({self.minutes})"
def __eq__(self, other):
if not isinstance(other, Duration):
return NotImplemented
return self.minutes == other.minutes
def __lt__(self, other):
if not isinstance(other, Duration):
return NotImplemented
return self.minutes < other.minutes
def __add__(self, other):
if not isinstance(other, Duration):
return NotImplemented
return Duration(self.minutes + other.minutes)The first two lines print:
[Duration(20), Duration(30), Duration(45)] Duration(45) True
Duration(65)and the last line’s traceback ends with:
TypeError: unsupported operand type(s) for +: 'int' and 'Duration'sorted compares with <, which is __lt__. max compares with >, and the first line also uses <=: total_ordering wrote both from __lt__ and __eq__. sum(talks) starts from 0: int’s __add__ returns NotImplemented for a Duration, and Duration has no __radd__ for Python to try next, so + raises TypeError. Start the sum from a duration instead, so every + is between two durations:
print(sum(talks, Duration(0)))Duration(95)Writing a __radd__ that accepts 0 would also work, but it would give 0 + Duration(5) a meaning, mixing plain numbers into durations; giving sum a start keeps the two types apart.
Exercise 15.5 (LO-15.3, ★★, about 15 minutes)¶
A class without __contains__, a special method this course doesn’t cover, gets in from
__iter__: x in route loops over the route until it finds x. With that, predict the three
lines this prints, then run it:
class Route:
"""A bus route: its stops, in order."""
def __init__(self, number, stops):
self.number = number
self.stops = list(stops)
self.position = 0
def __iter__(self):
return self
def __next__(self):
if self.position == len(self.stops):
raise StopIteration
stop = self.stops[self.position]
self.position += 1
return stop
route = Route(12, ["Station", "Library", "Market", "Harbor"])
print("Library" in route)
print(list(route))
print("Station" in route, list(route))Then change Route so that every line sees all four stops, give it __len__, and predict what
the three lines print with your new class, and what this fourth line prints:
print(len(route), max(route))Hint
Route.__iter__ returns self, so every loop shares one position. Which of the reading’s classes, Days or RainLog, makes a new iterator for each loop?
Answer
True
['Market', 'Harbor']
False []"Library" in route calls next until it finds "Library", which leaves position at 2. list(route) continues from there and leaves the route exhausted, so the last line finds nothing. A route isn’t something to use up: make it an iterable, which returns a new iterator each time, as RainLog does:
class Route:
"""A bus route: its stops, in order."""
def __init__(self, number, stops):
self.number = number
self.stops = list(stops)
def __len__(self):
return len(self.stops)
def __iter__(self):
return iter(self.stops)True
['Station', 'Library', 'Market', 'Harbor']
True ['Station', 'Library', 'Market', 'Harbor']
4 Stationposition and __next__ are gone: the list’s own iterator keeps each loop’s place. max compares strings alphabetically, and "Station" comes last.
Exercise 15.6 (LO-15.2, LO-15.3, LO-13.1, ★★★, about 20 minutes)¶
Build the stack that exercise 15.3 chose composition for, in stack.py:
push(item)puts an item on top.pop()removes the top item and returns it.peek()returns the top item without removing it.popandpeekraiseIndexErrorwhen the stack is empty, with a message that says so.len(stack)is the number of items, and aforloop gives the items from the top to the bottom, every time it runs.
Then write test_stack.py: the order pop returns items in, peek leaving the top item, two
loops in a row, both errors, and a test that a stack has no insert.
Hint
Keep the items in a list with the top at the end, where append and pop work. The slice [::-1], from Module 6, gives a reversed copy, and iter gives an iterator over it.
Answer
"""A stack, built by composition."""
class Stack:
"""Items in a stack: the last item pushed is the first popped."""
def __init__(self):
self._items = []
def push(self, item):
"""Put item on top."""
self._items.append(item)
def pop(self):
"""Remove the top item and return it."""
if not self._items:
raise IndexError("pop from an empty stack")
return self._items.pop()
def peek(self):
"""Return the top item without removing it."""
if not self._items:
raise IndexError("peek at an empty stack")
return self._items[-1]
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(self._items[::-1])import pytest
from stack import Stack
@pytest.fixture
def stack():
"""Return a stack holding 1, 2, and 3, with 3 on top."""
stack = Stack()
for item in [1, 2, 3]:
stack.push(item)
return stack
def test_pop_returns_the_last_item_pushed(stack):
assert [stack.pop(), stack.pop(), stack.pop()] == [3, 2, 1]
assert len(stack) == 0
def test_peek_leaves_the_top_item(stack):
assert stack.peek() == 3
assert len(stack) == 3
def test_iteration_goes_from_top_to_bottom_every_time(stack):
assert list(stack) == [3, 2, 1]
assert list(stack) == [3, 2, 1]
assert len(stack) == 3
def test_popping_an_empty_stack_says_so():
with pytest.raises(IndexError, match="empty stack"):
Stack().pop()
def test_peeking_at_an_empty_stack_says_so():
with pytest.raises(IndexError, match="empty stack"):
Stack().peek()
def test_a_stack_offers_no_way_into_the_middle(stack):
with pytest.raises(AttributeError):
stack.insert(0, 99)
assert list(stack) == [3, 2, 1]...... [100%]
6 passed in 0.01sWithout the check, pop on an empty stack would still raise IndexError, from the list inside, but its message, pop from empty list, names a list that callers of a stack never see. __iter__ returns an iterator over a reversed copy, so each loop starts again at the top, and a push or a pop in the middle of a loop doesn’t disturb it.