Python 3D Academyবাংলা

@contextmanager: a context manager from a generator

🌍 In real life. Cooking with a kitchen timer has three parts: start the timer, cook, then stop the timer, even if the food burns and you have to run to the sink.

Writing a whole class with __enter__ and __exit__ for that is a lot of typing. contextlib.contextmanager lets you write it as one generator function (Chapter 26) instead. Step by step:

  1. the code before yield is the setup (start the timer)
  2. yield hands control to the with block; the value it yields is what as names
  3. the code after yield is the clean-up (stop the timer)
  4. put the yield inside try/finally, so the clean-up runs even when the block raises an error

The idea in one sentence: @contextmanager turns a generator into a context manager: the code before yield is the setup, the yielded value goes after as, and the code after yield is the clean-up.

Its words:

  • from contextlib import contextmanager
  • one yield: the moment the with block runs
  • try/finally around the yield: makes the clean-up run even after an error
from contextlib import contextmanager

@contextmanager
def kitchen_timer(dish):
    print("timer started for", dish)
    try:
        yield "ding at 20 minutes"
    finally:
        print("timer stopped")

with kitchen_timer("rice") as note:
    print("cooking...", note)
print("dinner!")
@contextmanager writes the __enter__ and __exit__ for you: they run the generator up to yield, and then on to the end.

Why the try/finally matters. If the block raises an error, Python throws that error back in at the yield line. Without finally, the clean-up after yield would be skipped, like leaving the timer ringing. With it, the clean-up runs and then the error carries on:

from contextlib import contextmanager

@contextmanager
def kitchen_timer(dish):
    print("timer started for", dish)
    try:
        yield
    finally:
        print("timer stopped")

try:
    with kitchen_timer("fish"):
        print("cooking...")
        raise ValueError("burnt!")
except ValueError as e:
    print("oh no:", e)
from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")

with tag("ul"):
    with tag("li"):
        print("tea")
    with tag("li"):
        print("biscuits")
with blocks can sit inside each other: each one cleans up when its own block ends.

Mistakes and edge cases.

  • No yield. A function with no yield isn't a generator, so with fails with TypeError: 'NoneType' object is not an iterator.
  • Two yields. The with block runs only once, so a second yield gives RuntimeError: generator didn't stop.
  • No finally. If the block raises, the clean-up after yield is skipped (above).
  • Forgetting the decorator. Without @contextmanager, the generator has no __enter__ or __exit__.

Quiz

  1. What does this print?

    from contextlib import contextmanager
    
    @contextmanager
    def box():
        print("open")
        yield "toy"
        print("close")
    
    with box() as thing:
        print(thing)
  2. In a @contextmanager function, where does the with block run?

    • While the function is paused at yield
    • Before the function starts
    • After the function has finished
  3. What does this print?

    from contextlib import contextmanager
    
    @contextmanager
    def tag(name):
        print("<" + name + ">")
        yield
        print("</" + name + ">")
    
    with tag("b"):
        with tag("i"):
            print("hi")
  4. What does this print?

    from contextlib import contextmanager
    
    @contextmanager
    def guard():
        try:
            yield
        finally:
            print("cleaned")
    
    try:
        with guard():
            raise RuntimeError("stop")
    except RuntimeError:
        print("caught")
  5. Which line has a mistake?

    from contextlib import contextmanager
    
    @contextmanager
    def timer():
        print("start")
        return "go"
        print("stop")
    
    with timer() as t:
        print(t)

Coding tasks

  1. Write a context manager tag(name) with @contextmanager that prints <name> before the block and </name> after it.

  2. Write a context manager timer(log) with @contextmanager: it appends "start" to the list log on the way in and "stop" on the way out, even if the block raises an error. (run is written for you.)

  3. Write a context manager borrowed(shelf, book) with @contextmanager: it removes book from the list shelf, yields the book, and always puts it back at the end of the list. (read and drop are written for you.)