These exercises practice what the Module 16 reading explained. They aren’t graded.
Work in the folder m16 inside py101, where the reading’s access.log and weblog.py are, 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 file that is replaced whole, or not at all¶
A program that saves its data by writing over a file has a weak moment: if it crashes halfway
through the write, the old data is gone and the new data is cut short. The usual fix is to write
to a temporary file beside the real one, and to replace the real file with it only when the
writing has succeeded. A context manager is the right shape for this, because the decision
belongs after the block: replace the file if the block succeeded, and delete the temporary file if
it didn’t. Save this as atomic.py:
"""Write a file so that it is either replaced whole or left as it was."""
from contextlib import contextmanager
from pathlib import Path
@contextmanager
def atomic_write(path):
"""Write to a temporary file, and replace path with it only if the with block succeeds."""
path = Path(path)
temporary = path.with_name(path.name + ".tmp")
succeeded = False
try:
with open(temporary, "w", encoding="utf-8") as file:
yield file
succeeded = True
finally:
if succeeded:
temporary.replace(path)
else:
temporary.unlink(missing_ok=True)path.with_name(...) makes a path in the same folder with another name, here notes.txt.tmp for
notes.txt. The inner with closes the temporary file whether the block succeeds or not. The line
succeeded = True runs only if the block finished without an exception; if it raised, the
exception came out of the yield and skipped it. Then finally decides: temporary.replace(path)
renames the temporary file to the real name, replacing the old file, and temporary.unlink(...)
deletes the temporary file, where missing_ok=True means no error if it was never created. On
Linux and macOS, the replacement is atomic: another program sees the old file or the new one,
never part of either. Windows doesn’t promise that, but there too a failed write leaves the old
file as it was.
from pathlib import Path
from atomic import atomic_write
notes = Path("notes.txt")
notes.write_text("first version\n", encoding="utf-8")
try:
with atomic_write(notes) as file:
file.write("second version, half")
raise RuntimeError("the program crashed")
except RuntimeError as error:
print("caught:", error)
print(notes.read_text(encoding="utf-8"), end="")
print(Path("notes.txt.tmp").exists())
with atomic_write(notes) as file:
file.write("third version\n")
print(notes.read_text(encoding="utf-8"), end="")caught: the program crashed
first version
False
third versionThe failed write left first version in place and no temporary file behind; the next write
replaced it. The tests use pytest’s tmp_path fixture (Module 13), so each test gets an empty
folder of its own, and they check the folder’s contents, because a stray .tmp file is a bug too.
Save this as test_atomic.py:
import pytest
from atomic import atomic_write
def test_writes_a_new_file(tmp_path):
path = tmp_path / "new.txt"
with atomic_write(path) as file:
file.write("hello\n")
assert path.read_text(encoding="utf-8") == "hello\n"
def test_replaces_a_file_whole(tmp_path):
path = tmp_path / "notes.txt"
path.write_text("old\n", encoding="utf-8")
with atomic_write(path) as file:
file.write("new\n")
assert path.read_text(encoding="utf-8") == "new\n"
assert [item.name for item in tmp_path.iterdir()] == ["notes.txt"]
def test_a_failed_write_leaves_the_old_file(tmp_path):
path = tmp_path / "notes.txt"
path.write_text("old\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="crashed"):
with atomic_write(path) as file:
file.write("half")
raise RuntimeError("crashed")
assert path.read_text(encoding="utf-8") == "old\n"
assert [item.name for item in tmp_path.iterdir()] == ["notes.txt"]
def test_a_failed_write_creates_nothing(tmp_path):
path = tmp_path / "new.txt"
with pytest.raises(ValueError):
with atomic_write(path) as file:
file.write("half")
raise ValueError("bad data")
assert list(tmp_path.iterdir()) == [].... [100%]
4 passed in 0.02sExercises¶
Exercise 16.1 (LO-16.1, ★, about 10 minutes)¶
zip (Module 7) takes iterators too, and asks each for an item in turn. Predict what this prints,
then run it.
def letters():
for letter in "abc":
print("give", letter)
yield letter
pairs = zip(letters(), range(2))
print("zipped")
print(list(pairs))Hint
zip stops when one of its iterables runs out. To find that out, it has to ask each one for an item, in order: first letters(), then range(2).
Answer
zipped
give a
give b
give c
[('a', 0), ('b', 1)]zip is lazy, so zipped comes first. Then list asks zip for pairs. For the third pair, zip asks letters() first, which gives c, and then range(2), which has run out, so zip stops. The c was taken and thrown away: when you zip iterators of different lengths, the longer one loses an item.
Exercise 16.2 (LO-16.1, ★★, about 15 minutes)¶
Write a generator function, differences(numbers), that yields the change from each number to the
next: differences([3, 5, 4, 4, 9]) yields 2, -1, 0, and 5. It must work on any iterable,
generators included, so it can’t use indexes or len. With fewer than two numbers, it yields
nothing.
Hint
Remember the previous number in a local variable. The first number has no previous one, so it yields nothing; start the variable at None to mark that.
Answer
def differences(numbers):
"""Yield the change from each number to the next."""
previous = None
for number in numbers:
if previous is not None:
yield number - previous
previous = number
print(list(differences([3, 5, 4, 4, 9])))
print(list(differences([7])), list(differences([])))
temps = (reading for reading in [8.5, 9.0, 7.5])
print(list(differences(temps)))[2, -1, 0, 5]
[] []
[0.5, -1.5]if previous is not None, rather than if previous, matters: a previous number of 0 is false, and if previous would skip the difference after it. The standard library’s itertools.pairwise, since Python 3.10, yields the pairs of neighbors that this function subtracts.
Exercise 16.3 (LO-16.2, ★★, about 20 minutes)¶
Answer these questions about the reading’s access.log, each with a pipeline built on parse and
read_lines from weblog.py, which reads the file once and keeps no list of the requests:
How many requests for
/logingot status 404?What were the first three requests at or after noon on November 5, 2026? Print the day, the time, the path, and the status of each, and read no further than the third.
Which path had the most server errors (status 500 or more), and how many?
Hint
Count with
sum(1 for request in … if …).A day and a time in this log’s format compare correctly as text, because their parts are written with leading zeros, from the largest to the smallest. Filter with a generator expression, and stop with
islice.Count by path in a dictionary (Module 8), then use
maxwith akey.
Answer
from itertools import islice
from weblog import parse, read_lines
def requests():
return parse(read_lines("access.log"))
login_misses = sum(1 for request in requests()
if request["path"] == "/login" and request["status"] == 404)
print(login_misses)
after_noon = (request for request in requests()
if (request["day"], request["time"]) >= ("2026-11-05", "12:00:00"))
for request in islice(after_noon, 3):
print(request["day"], request["time"], request["path"], request["status"])
failures = {}
for request in requests():
if request["status"] >= 500:
failures[request["path"]] = failures.get(request["path"], 0) + 1
worst = max(failures, key=lambda path: failures[path])
print(worst, failures[worst])
print(failures)629
2026-11-05 12:00:03 /search 200
2026-11-05 12:00:04 / 200
2026-11-05 12:00:13 /index.html 200
/courses.html 224
{'/courses.html': 224, '/search': 185, '/': 195, '/login': 217, '/index.html': 201}requests() makes a new pipeline each time it is called, because a generator can be used only once. Comparing (day, time) tuples compares the days first and the times only on the same day. The dictionary of counts holds five entries, one for each path, however long the log is. The paths are chosen at random, so the differences between them mean nothing: in a real log, a path with many more failures than the others would be worth a look.
Exercise 16.4 (LO-16.2, ★★, about 15 minutes)¶
Write longest_dry_spell(amounts), which takes daily rain amounts in millimeters and returns the
length of the longest run of days without rain, or 0 if there is none. Use groupby. With
rain_mm = [0.0, 2.4, 0.0, 0.0, 0.0, 5.1, 0.0, 0.0, 1.2, 0.0, 0.0, 0.0, 0.0, 3.3]it returns 4.
Hint
Here groupby’s grouping by neighbors is what you want. Group by whether a day was dry, key=lambda mm: mm == 0, so each group is a run of dry days or a run of rainy ones.
Answer
from itertools import groupby
def longest_dry_spell(amounts):
"""Return the length of the longest run of days without rain."""
longest = 0
for dry, days in groupby(amounts, key=lambda mm: mm == 0):
if dry:
longest = max(longest, sum(1 for day in days))
return longest
print(longest_dry_spell(rain_mm), longest_dry_spell([]), longest_dry_spell([1.0, 0.5]))
print([(dry, len(list(days))) for dry, days in groupby(rain_mm, key=lambda mm: mm == 0)])4 0 0
[(True, 1), (False, 1), (True, 3), (False, 1), (True, 2), (False, 1), (True, 4), (False, 1)]The second line shows the runs groupby found: dry for 1 day, rainy for 1, dry for 3, and so on. Sorting first would be wrong here, because it would put all the dry days into one run of 10.
Exercise 16.5 (LO-16.3, ★★, about 15 minutes)¶
Write a decorator, once, for a function that should run only on its first call, such as one
that loads settings from a slow source: later calls return the first call’s result without
running the function again. Keep the function’s name with functools.wraps. If the first call
raises an exception, the next call should try again.
Hint
The wrapper needs two variables that outlive each call: whether the function has run, and its result. Keep them in the decorator, and declare them nonlocal in the wrapper.
Answer
import functools
def once(function):
"""Run function on the first call only, and return that first result on every later call."""
called = False
result = None
@functools.wraps(function)
def wrapper(*args, **kwargs):
nonlocal called, result
if not called:
result = function(*args, **kwargs)
called = True
return result
return wrapper
@once
def load_settings():
"""Read the settings, which is slow, so it should happen once."""
print("loading")
return {"units": "metric"}
print(load_settings())
print(load_settings())
print(load_settings() is load_settings(), load_settings.__name__)loading
{'units': 'metric'}
{'units': 'metric'}
True load_settingscalled = True comes after the call, so an exception leaves it False, and the next call tries again. A separate called flag, rather than testing result is None, also handles a function whose first result is None. Every call returns the same dictionary object, as is shows; a caller that changes it changes it for every later caller.
Exercise 16.6 (LO-16.3, ★★★, about 20 minutes)¶
A decorator can take arguments of its own, as in @retry(3, TimeoutError). Python evaluates
retry(3, TimeoutError) first, and uses the function it returns as the decorator. So retry is a
function that returns a decorator, which returns a wrapper: three levels of def.
Write retry(times, errors). The wrapper calls the function up to times times while it raises
one of errors, an exception class or a tuple of them, printing attempt N failed: <message>
after each failure. It returns the first result that comes back, and if every attempt fails, it
lets the last exception reach the caller. Exceptions not in errors aren’t retried. Test it with
this function, which fails or succeeds in the order outcomes gives:
outcomes = ["timed out", "timed out", "ok", "timed out", "timed out", "timed out"]
@retry(3, (TimeoutError, ConnectionError))
def fetch(page):
"""Pretend to fetch a page: fail or succeed in the order outcomes gives."""
outcome = outcomes.pop(0)
if outcome == "timed out":
raise TimeoutError(f"{page} timed out")
return f"<html>{page}</html>"
print(fetch("index"))
print(fetch.__name__)
try:
fetch("about")
except TimeoutError as error:
print("gave up:", error)Hint
except errors as error: works with a class or a tuple of classes in errors, as except (ValueError, KeyError): did in Module 12. Inside an except block, raise on its own raises the exception being handled again, unchanged.
Answer
import functools
def retry(times, errors):
"""Return a decorator that calls a function up to times times while it raises one of errors."""
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return function(*args, **kwargs)
except errors as error:
print(f"attempt {attempt} failed: {error}")
if attempt == times:
raise
return wrapper
return decoratorattempt 1 failed: index timed out
attempt 2 failed: index timed out
<html>index</html>
fetch
attempt 1 failed: about timed out
attempt 2 failed: about timed out
attempt 3 failed: about timed out
gave up: about timed outreturn inside the try ends the loop at the first success. After the last attempt, the bare raise passes the exception on, so the caller sees the real error. An exception that isn’t one of errors isn’t caught at all, and leaves on the first attempt. Real code usually also waits between attempts, longer each time, so that a struggling server gets a chance to recover; this version leaves that out.
Exercise 16.7 (LO-16.4, ★★, about 15 minutes)¶
Write a context manager, transaction(items), for a list. It yields the list itself. If the
with block succeeds, the block’s changes to the list stay; if the block raises, the list goes
back to exactly what it held before the block, and the exception continues to the caller. Test it
with:
basket = ["tea"]
with transaction(basket):
basket.append("milk")
print(basket)
try:
with transaction(basket) as items:
items.append("bread")
items.remove("cheese")
except ValueError as error:
print("failed:", error)
print(basket)Hint
Save a copy of the list before the yield, and use the worked example’s succeeded flag. To put the old items back into the same list object, which the caller’s name refers to, empty it with clear() and refill it with extend(saved). Assigning a new list to items would change only the local name.
Answer
from contextlib import contextmanager
@contextmanager
def transaction(items):
"""Keep the changes the with block makes to the list items only if the block succeeds."""
saved = list(items)
succeeded = False
try:
yield items
succeeded = True
finally:
if not succeeded:
items.clear()
items.extend(saved)['tea', 'milk']
failed: list.remove(x): x not in list
['tea', 'milk']The second block appended "bread" before remove failed, and the transaction took it out again. saved = list(items) is a copy, made before the block runs; saved = items would be a second name for the same list (Module 7), which the block would change too. Databases, in Module 17, work the same way: a transaction’s changes are all kept, or none are.