Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 16: Generators, decorators, and context managers

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.

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.

2. Writing generators

Exercise L16.2 (LO-16.1, ★★, about 20 minutes)

Write two generator functions:

  1. running_total(numbers) yields the total so far after each number: running_total([3, 1, 4]) yields 3, 4, and 8.

  2. chunks(items, size) yields lists of size items, 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]. items can be any iterable, a generator included, so don’t use len or slices on it, and yield each chunk as soon as it is full.

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.

  1. mean_size_with_list(lines) keeps the sizes in a list, then divides their sum by their number.

  2. 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.

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.

  1. first_paths(lines, status, n) returns a list of the paths of the first n requests with this status. Use a generator expression and islice.

  2. 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. Use groupby.

  3. 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. Use chain.

  4. none_missing(lines) returns True if no request has status 404, and stops reading at the first one that does. Use all or any.

5. Closures

Exercise L16.5 (LO-16.3, ★★, about 15 minutes)

  1. make_threshold(limit) returns a function that takes a request dictionary and returns True if its size is at least limit bytes.

  2. 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 use nonlocal.

6. A caching decorator

Exercise L16.6 (LO-16.3, ★★, about 25 minutes)

  1. Write memoized(function), a decorator that works like functools.cache for functions called with positional arguments: its wrapper keeps a dictionary that maps each tuple of arguments to the result, calls function only for arguments it hasn’t seen, and keeps the function’s name and docstring with functools.wraps.

  2. This function counts the paths across a grid of rows by cols squares, 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. Predict misses, the number of times the function body runs, which paths.cache_info().misses reports. The check runs it.

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)

  1. Predict c1, the value of first_run, and c2, the value of second_run.

  2. Write temporarily(dictionary, key, value), a context manager that sets dictionary[key] to value for the with block. When the block ends, however it ends, it puts back the old value, or removes the key if the dictionary didn’t have it.

Summary

  • A generator’s body runs only when next asks for an item, and pauses at each yield. A generator is used up after one pass.

  • mean_size_streaming kept 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, and any built pipelines that stopped reading as soon as they had their answer, which guarded checked.

  • Closures kept their own variables, and memoized used one to remember results, which turned an impossible number of calls into a few hundred.

  • A context manager’s finally runs however the block ends, which is what let temporarily restore the dictionary after an exception.