Objectives: LO-16.1, LO-16.2, LO-16.3, LO-16.4
Prerequisites: the Module 16 reading and
Lab 15
Time: about 2.5 hours
In this lab you predict when a generator’s body runs, write generators and measure the memory
they save, answer questions about a web server log with pipelines that read only what they
need, write closures and a caching decorator, and write a context manager that always cleans
up. Each exercise ends with a check cell that prints passed or says what is wrong.
Setup¶
Run the next cell first. log_lines makes the reading’s made-up access log in memory instead
of in a file: log_lines(100_000) yields the same 100,000 lines as the reading’s access.log,
one at a time. parse is the reading’s. peak_kb measures memory, as in the reading.
guarded passes items through, but raises AssertionError if more than limit are asked for;
the checks use it to test that your code reads no more than it needs.
import functools
import inspect
import random
import sys
import tracemalloc
from contextlib import contextmanager
from datetime import datetime, timedelta
from itertools import chain, count, groupby, islice
print("Python", sys.version.split()[0])
PATHS = ["/", "/index.html", "/courses.html", "/search", "/login"]
STATUSES = [200] * 90 + [304] * 6 + [404] * 3 + [500]
def log_lines(n, seed=16):
"""Yield n made-up access log lines; the same seed gives the same lines."""
rng = random.Random(seed) # Its own random numbers, which no other code can disturb.
moment = datetime(2026, 11, 2)
for _ in range(n):
moment += timedelta(seconds=rng.randint(1, 11))
status = rng.choice(STATUSES)
size = rng.randint(200, 20_000) if status == 200 else 0
stamp = moment.strftime("%Y-%m-%d %H:%M:%S")
yield f"{stamp} GET {rng.choice(PATHS)} {status} {size}"
def parse(lines):
"""Yield one dictionary for each log line."""
for line in lines:
day, time, method, path, status, size = line.split()
yield {"day": day, "time": time, "path": path, "status": int(status), "size": int(size)}
def peak_kb(function):
"""Run function, and return the most memory it held at once, in KB."""
tracemalloc.start()
try:
function()
return tracemalloc.get_traced_memory()[1] / 1000
finally:
tracemalloc.stop()
def guarded(items, limit):
"""Yield the items, but raise AssertionError if more than limit are asked for."""
for taken, item in enumerate(items, start=1):
if taken > limit:
raise AssertionError(
f"read more than {limit} items: yield each result as soon as it is ready, "
"and stop as soon as you have the answer"
)
yield item
for line in log_lines(3):
print(line)1. When the body runs¶
Read this code, but don’t run it yet. events records what the generator’s body does, and
list(events) takes a copy of it at that moment.
events = []
def numbered(items):
events.append("start")
for number, item in enumerate(items, start=1):
events.append(f"yield {number}")
yield f"{number}. {item}"
events.append("end")
shopping = numbered(["tea", "milk"])
after_call = list(events)
first = next(shopping)
after_first = list(events)
rest = list(shopping)
after_rest = list(events)
again = list(shopping)Exercise L16.1 (LO-16.1, ★, about 10 minutes)¶
Predict the value of each name: e1 for after_call, e2 for after_first, e3 for
after_rest, r1 for first, r2 for rest, and r3 for again.
e1 = []
e2 = []
e3 = []
r1 = "..."
r2 = []
r3 = []events = []
def numbered(items):
events.append("start")
for number, item in enumerate(items, start=1):
events.append(f"yield {number}")
yield f"{number}. {item}"
events.append("end")
shopping = numbered(["tea", "milk"])
after_call = list(events)
first = next(shopping)
after_first = list(events)
rest = list(shopping)
after_rest = list(events)
again = list(shopping)
print(after_call, after_first, after_rest, sep="\n")
print(repr(first), rest, again)assert e1 == [], "e1: calling a generator function doesn't run its body."
assert e2 == ["start", "yield 1"], "e2: next runs the body up to the first yield, and stops there."
assert e3 == ["start", "yield 1", "yield 2", "end"], (
"e3: list keeps calling next until the body ends."
)
assert r1 == "1. tea", "r1: the value the first yield handed out."
assert r2 == ["2. milk"], "r2: list continues from where next left off."
assert r3 == [], "r3: a generator is used up after one pass."
print("passed")2. Writing generators¶
Exercise L16.2 (LO-16.1, ★★, about 20 minutes)¶
Write two generator functions:
running_total(numbers)yields the total so far after each number:running_total([3, 1, 4])yields 3, 4, and 8.chunks(items, size)yields lists ofsizeitems, in order, and then a shorter list of whatever is left, if anything is:chunks(range(7), 3)yields[0, 1, 2],[3, 4, 5], and[6].itemscan be any iterable, a generator included, so don’t uselenor slices on it, and yield each chunk as soon as it is full.
def running_total(numbers):
"""Yield the total so far after each number."""
...
def chunks(items, size):
"""Yield lists of size items, and a last, shorter list of what is left."""
...for function in [running_total, chunks]:
assert inspect.isgeneratorfunction(function), (
f"{function.__name__} should be a generator function: use yield."
)
assert list(running_total([3, 1, 4])) == [3, 4, 8], f"Got {list(running_total([3, 1, 4]))}."
assert list(running_total([])) == [], "No numbers, no totals."
assert list(islice(running_total(guarded(count(1), 4)), 4)) == [1, 3, 6, 10], (
"running_total should work on an endless iterator, one number at a time."
)
assert list(chunks(range(7), 3)) == [[0, 1, 2], [3, 4, 5], [6]], f"Got {list(chunks(range(7), 3))}."
assert list(chunks(range(4), 2)) == [[0, 1], [2, 3]], (
f"chunks(range(4), 2) gave {list(chunks(range(4), 2))}: don't yield an empty last chunk."
)
assert list(chunks([], 3)) == [], "No items, no chunks."
assert [len(chunk) for chunk in chunks(log_lines(10), 4)] == [4, 4, 2], (
"chunks should take a generator, such as log_lines(10)."
)
assert list(islice(chunks(guarded(count(), 6), 2), 3)) == [[0, 1], [2, 3], [4, 5]], (
"chunks should yield each chunk as soon as it is full."
)
print("passed")3. Measuring memory¶
Exercise L16.3 (LO-16.1, ★★, about 20 minutes)¶
Write two functions that return the mean size of the successful responses (status 200) in
lines, an iterable of log lines. Both raise ValueError if there is no successful response.
mean_size_with_list(lines)keeps the sizes in a list, then divides their sum by their number.mean_size_streaming(lines)goes through the lines once, keeping a running count and a running total, and builds no list.
Then run the measuring cell, which takes about 10 seconds, and compare the two.
def mean_size_with_list(lines):
"""Return the mean size of the status-200 responses, keeping the sizes in a list."""
...
def mean_size_streaming(lines):
"""Return the mean size of the status-200 responses, in one pass with no list."""
...n = 100_000
with_list = peak_kb(lambda: mean_size_with_list(log_lines(n)))
streaming = peak_kb(lambda: mean_size_streaming(log_lines(n)))
print(f"with a list: {with_list:,.0f} KB, streaming: {streaming:,.1f} KB")expected = 0
successes = 0
for request in parse(log_lines(5_000)):
if request["status"] == 200:
expected += request["size"]
successes += 1
expected /= successes
for function in [mean_size_with_list, mean_size_streaming]:
got = function(log_lines(5_000))
assert got == expected, f"{function.__name__}(log_lines(5_000)) gave {got}, not {expected}."
for lines in [[], ["2026-11-02 00:00:06 GET / 404 0"]]:
try:
function(lines)
except ValueError:
pass
except ZeroDivisionError:
raise AssertionError(f"{function.__name__}({lines}) divided by 0: raise ValueError.")
else:
raise AssertionError(f"{function.__name__}({lines}) should raise ValueError.")
assert streaming < with_list / 20, (
f"Streaming held {streaming:.1f} KB, the list version {with_list:.0f} KB: "
"mean_size_streaming should keep only a count and a total."
)
print("passed")4. Pipelines with itertools¶
Exercise L16.4 (LO-16.2, ★★, about 25 minutes)¶
Write four functions. Each takes log lines in time order, uses parse, and reads no more lines
than it needs.
first_paths(lines, status, n)returns a list of the paths of the firstnrequests with this status. Use a generator expression andislice.errors_per_day(lines)returns a dictionary that maps each day in the log to its number of server errors (status 500 or more), with 0 for a day that has none. Usegroupby.server_errors_in(*sources)is a generator function that takes any number of sources of log lines, and yields the server errors of the first source, then those of the second, and so on, as dictionaries. Usechain.none_missing(lines)returnsTrueif no request has status 404, and stops reading at the first one that does. Useallorany.
def first_paths(lines, status, n):
"""Return the paths of the first n requests with this status."""
...
def errors_per_day(lines):
"""Return the number of server errors on each day in the log."""
...
def server_errors_in(*sources):
"""Yield the server errors in each source of log lines, one source after another."""
...
def none_missing(lines):
"""Return True if no request has status 404."""
...positions = {}
for position, request in enumerate(parse(log_lines(100_000)), start=1):
positions.setdefault(request["status"], []).append((position, request))
third_404 = positions[404][2][0]
expected_paths = [request["path"] for position, request in positions[404][:3]]
got = first_paths(guarded(log_lines(100_000), third_404), 404, 3)
assert got == expected_paths, f"first_paths(..., 404, 3) gave {got}, not {expected_paths}."
assert first_paths(log_lines(20), 500, 5) == [], "No server errors in the first 20 lines."
expected_days = {}
for request in parse(log_lines(100_000)):
expected_days.setdefault(request["day"], 0)
if request["status"] >= 500:
expected_days[request["day"]] += 1
got = errors_per_day(log_lines(100_000))
assert got == expected_days, f"errors_per_day gave {got},\nnot {expected_days}."
assert errors_per_day([]) == {}, "An empty log has no days."
two_days = ["2026-11-02 08:00:00 GET / 500 0", "2026-11-03 08:00:00 GET / 200 900"]
assert errors_per_day(two_days) == {"2026-11-02": 1, "2026-11-03": 0}, (
f"errors_per_day(two_days) gave {errors_per_day(two_days)}: include days without errors."
)
assert inspect.isgeneratorfunction(server_errors_in), "server_errors_in should use yield."
try:
errors = list(server_errors_in(log_lines(2_000, seed=1), log_lines(2_000, seed=2)))
except AttributeError:
raise AssertionError("chain should get the sources themselves: chain(*sources).")
expected_errors = [request for request in parse(chain(log_lines(2_000, seed=1),
log_lines(2_000, seed=2)))
if request["status"] >= 500]
assert errors == expected_errors, "server_errors_in should yield every error, in order."
assert list(server_errors_in()) == [], "No sources, no errors."
first_500 = positions[500][0][0]
assert next(server_errors_in(guarded(log_lines(100_000), first_500))) == positions[500][0][1], (
"server_errors_in should yield the first error as soon as it is found."
)
first_404 = positions[404][0][0]
assert none_missing(guarded(log_lines(100_000), first_404)) is False, (
"none_missing should return False at the first 404."
)
assert none_missing(log_lines(first_404 - 1)) is True, "No 404 before the first one."
assert none_missing([]) is True, "An empty log has no 404."
print("passed")5. Closures¶
Exercise L16.5 (LO-16.3, ★★, about 15 minutes)¶
make_threshold(limit)returns a function that takes a request dictionary and returnsTrueif its size is at leastlimitbytes.make_averager()returns a function that takes a number and returns the mean of every number it has been given so far: given 10, then 20, then 0, it returns 10.0, 15.0, and 10.0. Keep a count and a total in the enclosing function, and usenonlocal.
def make_threshold(limit):
"""Return a function that tells whether a request's size is at least limit bytes."""
...
def make_averager():
"""Return a function that returns the mean of every number it has been given."""
...large = make_threshold(15_000)
small = make_threshold(500)
requests = list(parse(log_lines(1_000)))
assert callable(large), "make_threshold should return a function."
assert sum(1 for request in requests if large(request)) == sum(
1 for request in requests if request["size"] >= 15_000
), "large should be True for sizes of 15,000 bytes or more."
assert small({"size": 500}) is True and small({"size": 499}) is False, "At least limit: 500 counts."
assert large({"size": 500}) is False, "Each threshold keeps its own limit."
rain, wind = make_averager(), make_averager()
assert [rain(10), rain(20), rain(0)] == [10.0, 15.0, 10.0], "The means so far: 10, 15, then 10."
assert wind(7) == 7.0, "Each averager keeps its own count and total."
assert rain(30) == 15.0, "rain has now seen 10, 20, 0, and 30."
print("passed")6. A caching decorator¶
Exercise L16.6 (LO-16.3, ★★, about 25 minutes)¶
Write
memoized(function), a decorator that works likefunctools.cachefor functions called with positional arguments: its wrapper keeps a dictionary that maps each tuple of arguments to the result, callsfunctiononly for arguments it hasn’t seen, and keeps the function’s name and docstring withfunctools.wraps.This function counts the paths across a grid of
rowsbycolssquares, from one corner to the opposite one, moving only right or down:def paths(rows, cols): if rows == 0 or cols == 0: return 1 return paths(rows - 1, cols) + paths(rows, cols - 1)Decorated with
@functools.cache,paths(3, 3)returns 20. Predictmisses, the number of times the function body runs, whichpaths.cache_info().missesreports. The check runs it.
def memoized(function):
"""Remember function's result for each tuple of arguments."""
...
misses = 0calls = []
@memoized
def square(x):
"""Return x squared."""
calls.append(x)
return x * x
assert callable(square), "memoized should return the wrapper function."
assert [square(3), square(4), square(3), square(4)] == [9, 16, 9, 16], "square should still square."
assert calls == [3, 4], f"The body ran for {calls}: it should run once for each argument."
assert (square.__name__, square.__doc__) == ("square", "Return x squared."), (
"Use functools.wraps to keep the name and the docstring."
)
@memoized
def grid_paths(rows, cols):
"""Return the number of paths across a grid, moving only right or down."""
if rows == 0 or cols == 0:
return 1
return grid_paths(rows - 1, cols) + grid_paths(rows, cols - 1)
assert grid_paths(2, 3) == grid_paths(3, 2) == 10, "Different arguments need different entries."
assert grid_paths(16, 16) == 601_080_390, "grid_paths(16, 16) should be 601,080,390."
@functools.cache
def paths(rows, cols):
if rows == 0 or cols == 0:
return 1
return paths(rows - 1, cols) + paths(rows, cols - 1)
assert paths(3, 3) == 20
print(paths.cache_info())
assert misses == paths.cache_info().misses, (
"misses: count the different (rows, cols) pairs the calls reach, from (3, 3) down to the edges."
)
print("passed")Without a cache, grid_paths(16, 16) would make more than a billion calls, and the check would
never finish: the cache is what makes it take a moment.
7. Context managers¶
Read this code, but don’t run it yet.
events = []
@contextmanager
def section(name):
events.append(f"enter {name}")
try:
yield name.upper()
finally:
events.append(f"exit {name}")
with section("a") as label:
events.append(label)
with section("b"):
events.append("inside")
first_run = list(events)
events.clear()
try:
with section("c"):
events.append("before")
raise ValueError("stop")
events.append("after")
except ValueError:
events.append("caught")
second_run = list(events)Exercise L16.7 (LO-16.4, ★★, about 20 minutes)¶
Predict
c1, the value offirst_run, andc2, the value ofsecond_run.Write
temporarily(dictionary, key, value), a context manager that setsdictionary[key]tovaluefor thewithblock. When the block ends, however it ends, it puts back the old value, or removes the key if the dictionary didn’t have it.
c1 = []
c2 = []
@contextmanager
def temporarily(dictionary, key, value):
"""Set dictionary[key] to value for the with block, then restore it."""
...events = []
@contextmanager
def section(name):
events.append(f"enter {name}")
try:
yield name.upper()
finally:
events.append(f"exit {name}")
with section("a") as label:
events.append(label)
with section("b"):
events.append("inside")
first_run = list(events)
events.clear()
try:
with section("c"):
events.append("before")
raise ValueError("stop")
events.append("after")
except ValueError:
events.append("caught")
second_run = list(events)
print(first_run, second_run, sep="\n")
assert c1 == ["enter a", "A", "enter b", "inside", "exit b", "exit a"], (
"c1: the inner block exits before the outer one, and label is what yield handed out."
)
assert c2 == ["enter c", "before", "exit c", "caught"], (
"c2: the raise skips the rest of the block, the finally still runs, then except catches it."
)
settings = {"units": "metric", "verbose": False}
with temporarily(settings, "verbose", True):
assert settings == {"units": "metric", "verbose": True}, "Set the key inside the block."
assert settings == {"units": "metric", "verbose": False}, "Put the old value back after the block."
with temporarily(settings, "debug", 1):
assert settings["debug"] == 1, "Set a new key inside the block."
assert "debug" not in settings, "Remove a key that the dictionary didn't have before."
try:
with temporarily(settings, "units", "imperial"):
raise KeyError("boom")
except KeyError:
pass
else:
raise AssertionError("The exception from the block should reach the caller.")
assert settings["units"] == "metric", "Restore the value even when the block raises: use finally."
print("passed")Summary¶
A generator’s body runs only when
nextasks for an item, and pauses at eachyield. A generator is used up after one pass.mean_size_streamingkept a count and a total and held a few KB, where the list version held megabytes: memory that grows with the data, or doesn’t.islice,groupby,chain,all, andanybuilt pipelines that stopped reading as soon as they had their answer, whichguardedchecked.Closures kept their own variables, and
memoizedused one to remember results, which turned an impossible number of calls into a few hundred.A context manager’s
finallyruns however the block ends, which is what lettemporarilyrestore the dictionary after an exception.