@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:
- the code before
yieldis the setup (start the timer) yieldhands control to thewithblock; the value it yields is whatasnames- the code after
yieldis the clean-up (stop the timer) - put the
yieldinsidetry/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
withblock runs try/finallyaround theyield: 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!")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")Mistakes and edge cases.
- No yield. A function with no
yieldisn't a generator, sowithfails withTypeError: 'NoneType' object is not an iterator. - Two yields. The
withblock runs only once, so a secondyieldgivesRuntimeError: generator didn't stop. - No finally. If the block raises, the clean-up after
yieldis skipped (above). - Forgetting the decorator. Without
@contextmanager, the generator has no__enter__or__exit__.
Quiz
What does this print?
from contextlib import contextmanager @contextmanager def box(): print("open") yield "toy" print("close") with box() as thing: print(thing)In a
@contextmanagerfunction, where does thewithblock run?- While the function is paused at yield
- Before the function starts
- After the function has finished
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")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")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
Write a context manager
tag(name)with@contextmanagerthat prints<name>before the block and</name>after it.Write a context manager
timer(log)with@contextmanager: it appends"start"to the listlogon the way in and"stop"on the way out, even if the block raises an error. (runis written for you.)Write a context manager
borrowed(shelf, book)with@contextmanager: it removesbookfrom the listshelf, yields the book, and always puts it back at the end of the list. (readanddropare written for you.)