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.

Module 16: Generators, decorators, and context managers

Objectives: LO-16.1, LO-16.2, LO-16.3, LO-16.4
Prerequisites: Module 7 and Module 15
Time: about 7 hours: 2.5 for this reading, 2.5 for Lab 16, and 2 for the practice

Module 15’s Days iterator needed a class, two special methods, and an attribute to remember its place. This module starts with generators, which make an iterator from an ordinary function and produce one item at a time, so a program can work through more data than fits in memory. It then turns to functions that make and change other functions: closures, and decorators, which add behavior such as timing or caching to a function without changing its code. It ends with context managers, which guarantee that cleanup runs, as with open(...) does for files.

Work in a new folder, m16, in your py101 folder, and save each example there.

Generators

Generator functions

A function that contains yield is a generator function. Calling it doesn’t run its body: it returns a generator, which is an iterator. Each next runs the body until the next yield, which hands out a value and pauses the function where it is, local variables and all. The next next continues from that point. When the body ends, the generator raises StopIteration, as Module 15’s iterators did. Save this as countdown.py, and run it:

def countdown(n):
    """Yield n, n - 1, and so on down to 1."""
    print("starting")
    while n > 0:
        yield n
        n -= 1
    print("done")


numbers = countdown(3)
print(type(numbers).__name__)
print(next(numbers))
print(next(numbers))
for number in numbers:
    print("loop got", number)
print(list(numbers))
generator
starting
3
2
loop got 1
done
[]

countdown(3) printed nothing, because the body hadn’t started. The first next ran it from the top to the first yield, printing starting and handing out 3. The second next continued after that yield, went around the loop once, and handed out 2. The for loop took over from there: it got 1, and its next call ran the body to the end, which printed done and raised StopIteration, ending the loop. A generator is an iterator, so like Days it is used up after one pass, and list(numbers) is empty.

Here is Module 15’s Days as a generator function. Save it as days.py:

from datetime import timedelta


def days(first, last):
    """Yield the dates from first to last, both included."""
    day = first
    while day <= last:
        yield day
        day += timedelta(days=1)

Python writes __iter__ and __next__, and the local variable day keeps the place that Days kept in an attribute. list(days(date(2026, 11, 28), date(2026, 12, 1))) gives the same four dates as before. Each call of days makes a new generator, so to go through the dates again, call it again.

Generator expressions

A generator expression is a list comprehension (Module 7) in parentheses instead of square brackets. It makes a generator instead of a list:

squares = (x * x for x in range(5))
print(next(squares), list(squares))
print(sum(x * x for x in range(5)))
0 [1, 4, 9, 16]
30

When a generator expression is the only argument of a call, its own parentheses can be left out, as in sum(x * x for x in range(5)).

Measuring the memory a generator saves

A list holds all its items at once. A generator holds only its paused state, and makes each item when asked. The tracemalloc module, in the standard library, traces the memory Python allocates; its get_traced_memory() returns two numbers, the memory held now and the most held at once since tracing started (the peak). Save this as memory.py:

import tracemalloc


def peak_kb(function):
    """Run function, and return the most memory it held at once, in KB."""
    tracemalloc.start()
    function()
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return peak / 1000


n = 1_000_000
with_list = peak_kb(lambda: sum([x * x for x in range(n)]))
with_generator = peak_kb(lambda: sum(x * x for x in range(n)))
print(f"list: {with_list:,.1f} KB, generator: {with_generator:,.1f} KB")

On a laptop with an Intel Core i7-11800H processor, running Linux and Python 3.12.3, it printed the same line every time:

list: 40,448.2 KB, generator: 0.5 KB

The list version held about 40 MB at its peak: a million squares, each a separate int object of 32 bytes, and the list’s own reference to each one, 8 bytes more. The generator version never held more than one square at a time. The two sum calls give the same answer. Your numbers may differ a little with the Python version and the operating system, but not by much, because they count allocations rather than time.

Saving memory didn’t cost time here. Timing each version 10 times with timeit, as in Module 8, printed:

list: 0.44 s, generator: 0.40 s
list: 0.45 s, generator: 0.41 s
list: 0.53 s, generator: 0.47 s

That isn’t a rule: a generator is sometimes a little slower. Choose a list when you need what only a list can do: its length, an item by index, or more than one pass over the items. Choose a generator when each item is used once, in order, and especially when the items wouldn’t all fit in memory.

Pipelines of generators

A log, one line at a time

A web server writes a line to its access log for each request it answers: when, which page, the status (200 for success, 304 for “not modified”, 404 for “not found”, and 500 or more for a failure on the server), and the size of the response in bytes. This script writes a made-up log of 100,000 requests over a week, the same every time, because it seeds the random numbers. Save it as make_log.py, and run it:

"""Write access.log: a made-up web server log, the same every time."""

import random
from datetime import datetime, timedelta

PATHS = ["/", "/index.html", "/courses.html", "/search", "/login"]
STATUSES = [200] * 90 + [304] * 6 + [404] * 3 + [500]

random.seed(16)
moment = datetime(2026, 11, 2)
with open("access.log", "w", encoding="utf-8") as log:
    for _ in range(100_000):
        moment += timedelta(seconds=random.randint(1, 11))
        status = random.choice(STATUSES)
        size = random.randint(200, 20_000) if status == 200 else 0
        stamp = moment.strftime("%Y-%m-%d %H:%M:%S")
        log.write(f"{stamp} GET {random.choice(PATHS)} {status} {size}\n")
print("Wrote access.log: 100,000 requests.")

A datetime is a date with a time of day. random.choice(STATUSES) picks 200 about 90 percent of the time, because 200 fills 90 of the list’s 100 places. The file is 4.2 MB, and starts:

2026-11-02 00:00:06 GET /courses.html 200 15944
2026-11-02 00:00:13 GET / 200 14839
2026-11-02 00:00:20 GET /index.html 200 8682

Each step of the work can be a generator that takes an iterator and yields the results, so the steps join like pipes. Save this as weblog.py:

"""Read a web server log as a pipeline of generators."""


def read_lines(path):
    """Yield each line of the file at path, without its newline."""
    with open(path, encoding="utf-8") as file:
        for line in file:
            yield line.rstrip("\n")


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 server_errors(requests):
    """Yield the requests that failed on the server: status 500 or more."""
    for request in requests:
        if request["status"] >= 500:
            yield request
from weblog import parse, read_lines, server_errors

requests = parse(read_lines("access.log"))
total = sum(request["size"] for request in requests)
print(f"{total / 1_000_000:.1f} MB sent")

errors = server_errors(parse(read_lines("access.log")))
print(next(errors))
910.4 MB sent
{'day': '2026-11-02', 'time': '00:16:10', 'path': '/courses.html', 'status': 500, 'size': 0}

No step runs until sum asks for a value. Then sum asks the generator expression for a size, which asks parse for a request, which asks read_lines for a line, which reads one line from the file: a file object is itself an iterator over its lines. One line travels the whole pipeline before the next is read. The second pipeline reads only as far as the first server error, 16 minutes into the log. The file stays open until that generator is discarded, which CPython, the usual Python, does as soon as nothing refers to it.

To see what the pipeline saves, compare it with the same steps done with lists, each step kept whole before the next starts. Save this as compare.py:

import tracemalloc

from weblog import parse, read_lines


def total_with_lists(path):
    lines = list(read_lines(path))
    requests = list(parse(lines))
    return sum([request["size"] for request in requests])


def total_with_generators(path):
    return sum(request["size"] for request in parse(read_lines(path)))


for function in [total_with_lists, total_with_generators]:
    tracemalloc.start()
    total = function("access.log")
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    print(f"{function.__name__}: {total:,} bytes sent, peak memory {peak / 1000:,.0f} KB")
total_with_lists: 910,412,359 bytes sent, peak memory 45,770 KB
total_with_generators: 910,412,359 bytes sent, peak memory 23 KB

The answers match, and the pipeline used about one two-thousandth of the memory. The difference grows with the file: the lists grow with every line, while the pipeline holds one line and one request whatever the file’s size.

Tools for iterators: itertools

The standard library’s itertools module has functions that take iterators and return iterators, so they fit into pipelines. Four of the most used:

from itertools import chain, count, groupby, islice

from weblog import parse, read_lines, server_errors

errors = server_errors(parse(read_lines("access.log")))
for request in islice(errors, 3):
    print(request["day"], request["time"], request["path"])

print(list(islice(count(10, 5), 4)))

print(list(chain([1, 2], (3, 4), "ab")))

requests = parse(read_lines("access.log"))
for day, group in groupby(requests, key=lambda request: request["day"]):
    print(day, sum(1 for request in group))
2026-11-02 00:16:10 /courses.html
2026-11-02 00:21:09 /search
2026-11-02 00:22:14 /
[10, 15, 20, 25]
[1, 2, 3, 4, 'a', 'b']
2026-11-02 14378
2026-11-03 14382
2026-11-04 14452
2026-11-05 14365
2026-11-06 14468
2026-11-07 14341
2026-11-08 13614

islice stopped the error pipeline after three errors, and stopped the endless count after four numbers. sum(1 for request in group) counts the items in an iterator without building a list. The last day is short because the log ends on November 8 at 22:45.

groupby groups only items that are next to each other. The log is in time order, so each day’s requests are together. When equal keys are scattered, sort by the key first:

from itertools import groupby

statuses = [200, 200, 404, 200, 500, 404]
print([(status, len(list(group))) for status, group in groupby(statuses)])
print([(status, len(list(group))) for status, group in groupby(sorted(statuses))])
[(200, 2), (404, 1), (200, 1), (500, 1), (404, 1)]
[(200, 3), (404, 2), (500, 1)]

Without a key, groupby groups by the items themselves. Sorting builds a list, so for data too large for memory, a dictionary of counts (Module 8) is the usual way to count by a key that isn’t in order.

Built-ins that consume iterators

sum, min, max, sorted, any, and all take any iterable, generators included. any returns True as soon as one item is true, and all returns False as soon as one item is false, so neither reads further than it needs to. This generator says which item it hands out:

def checked(values):
    """Yield each value, saying so first."""
    for value in values:
        print("checking", value)
        yield value


print(any(status >= 500 for status in checked([200, 500, 404, 200])))
print(all(status < 400 for status in checked([200, 304, 404, 200])))
checking 200
checking 500
True
checking 200
checking 304
checking 404
False

max with key, from Module 7, works on a pipeline too, and reads it once:

from weblog import parse, read_lines

requests = parse(read_lines("access.log"))
print(max(requests, key=lambda request: request["size"]))
{'day': '2026-11-07', 'time': '09:57:10', 'path': '/', 'status': 200, 'size': 20000}

Two responses have the largest size, 20,000 bytes; max returns the first of them.

Functions that make functions

Closures

Functions are values, like numbers and lists: a name can refer to one, a list can hold one, and a function can take one as an argument, as sorted and max take key. A function can also define a function inside itself and return it. Save this as converters.py:

def make_converter(factor, offset):
    """Return a function that converts a value to value * factor + offset."""

    def convert(value):
        return value * factor + offset

    return convert


to_fahrenheit = make_converter(1.8, 32)
to_kelvin = make_converter(1, 273.15)
print(to_fahrenheit(20), to_kelvin(20), to_fahrenheit(-40))
print(to_fahrenheit.__name__)
68.0 293.15 -40.0
convert

convert uses factor and offset, which belong to the call of make_converter that created it. That call has returned, but convert keeps its variables alive: a function that uses the variables of an enclosing function is a closure. Each call of make_converter makes a new convert with its own factor and offset, which is why to_fahrenheit and to_kelvin differ.

A closure that assigns to an enclosing variable must say so with nonlocal. Save this as counter.py:

def make_counter():
    """Return a function that returns 1, 2, 3, and so on, one more on each call."""
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter


tickets = make_counter()
orders = make_counter()
print(tickets(), tickets(), tickets(), orders())
1 2 3 1

Without the nonlocal line, the first call raises UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. It is Module 5’s rule for local names: count += 1 assigns to count, so Python makes count a local variable of counter, and that local has no value yet when += reads it. nonlocal count says that count belongs to the enclosing function, as global says a name belongs to the module.

Decorators

Any arguments: *args and **kwargs

A decorator wraps functions it knows nothing about, so it needs a way to accept any arguments and pass them on. In a def, *args collects the positional arguments into a tuple, and **kwargs collects the keyword arguments into a dictionary. In a call, * and ** do the opposite: they spread a sequence into positional arguments and a dictionary into keyword arguments. The names args and kwargs are only a convention; the stars do the work.

def show(*args, **kwargs):
    print(args, kwargs)


show(1, "two", unit="mm")
show()
numbers = [3, 4]
options = {"sep": " -> "}
print(*numbers, **options)
(1, 'two') {'unit': 'mm'}
() {}
3 -> 4

The last line is the call print(3, 4, sep=" -> ").

Writing a decorator

A decorator is a function that takes a function and returns a replacement for it, usually a closure that calls the original and does something before or after. Save this as decorators.py:

"""Decorators that time and count calls."""

import functools
import time


def timed(function):
    """Print how long each call of function takes."""

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = function(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{function.__name__} took {elapsed:.3f} s")
        return result

    return wrapper


def counted(function):
    """Count the calls of function, in the wrapper's calls attribute."""

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return function(*args, **kwargs)

    wrapper.calls = 0
    return wrapper

time.perf_counter() returns a time in seconds from a clock made for measuring short intervals; only the difference between two readings means anything. wrapper passes on whatever arguments it gets, and returns what function returned, so callers can’t tell it from the original except for its extra work. counted keeps its count in an attribute of the wrapper itself, which works because a function is an object. The @functools.wraps(function) line in each is explained in the next section.

Writing @timed on the line above a def applies the decorator: it is the same as writing bytes_sent = timed(bytes_sent) after the definition.

from decorators import timed
from weblog import parse, read_lines


@timed
def bytes_sent(path):
    """Return the total size of the responses in the log at path."""
    return sum(request["size"] for request in parse(read_lines(path)))


total = bytes_sent("access.log")
print(total, bytes_sent.__name__, bytes_sent.__doc__)
bytes_sent took 0.093 s
910412359 bytes_sent Return the total size of the responses in the log at path.

The time differs from run to run: three runs took 0.093, 0.065, and 0.075 s.

Keeping the function’s name: functools.wraps

@functools.wraps(function) is itself a decorator, applied to wrapper. It copies the original function’s name, docstring, and a few other attributes onto the wrapper. Without it, the decorated function takes the wrapper’s name and loses its docstring: with the @functools.wraps line removed from timed, the last line above prints 910412359 wrapper None. help would then describe wrapper, and so would a second decorator stacked on top: with @timed above @counted, and neither using functools.wraps, the timing message starts wrapper took instead of bytes_sent took, because the function timed wraps is counted’s wrapper. Use functools.wraps in every decorator.

Caching results: functools.cache

This function counts the ways to make an amount, in cents, from coins of 50, 20, 10, 5, 2, and 1 cents. Either the first coin is used at least once, which leaves amount - coins[0] to make with the same coins, or it isn’t used at all, which leaves amount to make with the other coins; the answer is the sum of the two. Save it as coins.py:

from decorators import counted

COINS = (50, 20, 10, 5, 2, 1)


@counted
def ways(amount, coins):
    """Return the number of ways to make amount from coins, each used any number of times."""
    if amount == 0:
        return 1
    if amount < 0 or not coins:
        return 0
    return ways(amount - coins[0], coins) + ways(amount, coins[1:])


print(ways(100, COINS), ways.calls)
4562 209415

There are 4,562 ways to make 100 cents, but finding them took 209,415 calls, because the same smaller questions come up again and again. functools.cache remembers each answer, by its arguments, and returns it the next time without running the function. In coins.py, replace from decorators import counted with import functools, replace @counted with @functools.cache, and change the last line:

print(ways(100, COINS), ways.cache_info())
4562 CacheInfo(hits=131, misses=346, maxsize=None, currsize=346)

The function ran 346 times, once for each different pair of arguments (the misses), and 131 calls were answered from the cache (the hits): 477 calls instead of 209,415. A cache fits only some functions:

Context managers

What with guarantees

with open(path) as file: closes the file when the block ends, however it ends: at its last line, at a return, or with an exception. Module 12’s finally gives the same guarantee, and this code does what a with block does:

file = open("access.log", encoding="utf-8")
try:
    first = next(file)
finally:
    file.close()
print(first.split()[3], file.closed)
/courses.html True

An object that can be used in a with statement is a context manager. Files are context managers, and so is pytest.raises from Module 13. Any resource that must be released, such as a file, a network connection, or a lock, should be used through one, so that an exception can’t skip the release.

Writing one with contextlib.contextmanager

The decorator contextlib.contextmanager turns a generator function that yields once into a context manager. The code before the yield runs when the with block starts, the block runs at the yield, and the code after it runs when the block ends. Save this as timer.py:

"""A context manager that times a block of code."""

import time
from contextlib import contextmanager


@contextmanager
def timer(label):
    """Time the with block, and print how long it took, even if it fails."""
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"{label}: {time.perf_counter() - start:.3f} s")
from timer import timer
from weblog import parse, read_lines

with timer("count"):
    requests = sum(1 for request in parse(read_lines("access.log")))
print(requests, "requests")

with timer("parse a bad line"):
    list(parse(["2026-11-02 00:00:06 GET / 200"]))
print("not reached")
count: 0.077 s
100000 requests
parse a bad line: 0.000 s

The second block fails, because the line has five fields instead of six. The timer still prints, and then the exception continues on its way, and its traceback ends with:

ValueError: not enough values to unpack (expected 6, got 5)

The try and finally around the yield are what make the cleanup run. An exception in the block is raised inside the generator, at the yield: without finally, it would leave the generator at once, the line after yield would never run, and the timer would print nothing.

Giving the block a value

A value after yield becomes the value after as in the with statement:

from contextlib import contextmanager


@contextmanager
def opened_log(path):
    """Open the log at path for reading, and close it after the with block."""
    file = open(path, encoding="utf-8")
    print("opened", path)
    try:
        yield file
    finally:
        file.close()
        print("closed", path)


with opened_log("access.log") as log:
    print(next(log).split()[3])
print(log.closed)
opened access.log
/courses.html
closed access.log
True

open already does this, of course; opened_log only shows where each part runs. The practice builds a context manager that open can’t replace.

Common misconceptions

MisconceptionWhat’s trueAn example that breaks it
Calling a generator function runs itIt returns a generator, and the body runs only when next asks for an itemcountdown(3) prints nothing until the first next
A generator can be looped over againA generator is an iterator, used up after one passAfter a loop over numbers, list(numbers) is []
groupby puts all equal items in one groupIt groups only runs of neighborsgroupby([200, 200, 404, 200]) gives two groups of 200
A decorated function keeps its nameOnly if the decorator uses functools.wrapsWithout it, bytes_sent.__name__ is 'wrapper'
functools.cache speeds up any functionOnly one whose arguments are hashable and whose result depends on nothing elseA cached ways called with a list raises TypeError: unhashable type: 'list'
The code after yield in a context manager always runsOnly if it is in a finally blockA timer without try and finally prints nothing when its block raises

Summary

Self-check

  1. What does this print?

    def pairs(items):
        print("start")
        for i in range(len(items) - 1):
            yield items[i], items[i + 1]
    
    
    p = pairs([1, 2, 3])
    print("made")
    print(list(p), list(p))

    Answer

    made
    start
    [(1, 2), (2, 3)] []

    Calling pairs runs nothing, so made comes first. The first list runs the body, which prints start and yields two pairs; the second list gets nothing, because the generator is used up.

  2. Rewrite this function as a generator function, so that it can filter a file of any size:

    def long_words(words, n):
        result = []
        for word in words:
            if len(word) > n:
                result.append(word)
        return result

    Answer

    def long_words(words, n):
        for word in words:
            if len(word) > n:
                yield word

    list(long_words(["to", "iterate", "is", "human"], 3)) gives ['iterate', 'human']. A generator expression does the same: (word for word in words if len(word) > n).

  3. What does [key for key, group in groupby(["b", "a", "b"])] give, and how do you get one group for each letter?

    Answer

    ['b', 'a', 'b']: the two "b" items aren’t neighbors, so they form two groups. Sort first: groupby(sorted(["b", "a", "b"])) gives the keys 'a' and 'b'.

  4. Write a decorator, logged, that prints the name of the function and the arguments of each call before making it. What does area(3, height=4) print, where area returns width * height and is decorated with @logged?

    Answer

    import functools
    
    
    def logged(function):
        """Print each call of function and its arguments."""
    
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            print(f"calling {function.__name__} with {args} {kwargs}")
            return function(*args, **kwargs)
    
        return wrapper

    With print(area(3, height=4)), it prints:

    calling area with (3,) {'height': 4}
    12

    args is a tuple of one item, which Python writes as (3,).

  5. A context manager made with contextlib.contextmanager releases a resource on the line after its yield, with no try. What happens when the with block raises an exception?

    Answer

    The exception is raised inside the generator at the yield, and leaves it at once, so the line after yield never runs and the resource is never released. Put the release in a finally block around the yield.

Further reading