Sub topic 6
Writing a context manager with @contextmanager
This chapter assumes you know Python functions, generators and yield, basic decorators, try/finally, and the class-based __enter__/__exit__ protocol from the previous chapter.
Why a second way to write managers
A class-based manager needs a class, two methods, and often stored state. For simple setup-and-cleanup logic that is a lot of ceremony. The contextlib.contextmanager decorator lets you write the same thing as one generator function.
The rule is simple. The code before yield is the setup. The value you yield goes to the as clause. The code after yield is the cleanup.
A first example
import os
from contextlib import contextmanager
@contextmanager
def working_directory(path):
previous = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(previous)
with working_directory("/tmp") as cwd:
print(os.getcwd())Calling working_directory("/tmp") does not run the function body. It returns a context manager object that wraps the generator. The body runs in stages as the with statement proceeds.
What happens at each step
withcalls__enter__on the wrapper. The wrapper advances the generator to itsyield.- The yielded value is returned from
__enter__and bound to the name afteras. - The body of the
withblock runs. - On exit,
__exit__resumes the generator. If the body finished normally, the generator continues afteryield. If the body raised, the exception is thrown into the generator at theyieldline.
Always use try/finally around the yield
Step 4 explains the most common mistake. If the body raises, the exception appears at the yield line inside your generator. Code after yield that is not in a finally block is skipped.
from contextlib import contextmanager
@contextmanager
def broken():
print("setup")
yield
print("cleanup") # skipped if the body raises
@contextmanager
def correct():
print("setup")
try:
yield
finally:
print("cleanup") # always runs
try:
with broken():
raise ValueError("boom")
except ValueError:
print("broken: no cleanup was printed")
try:
with correct():
raise ValueError("boom")
except ValueError:
print("correct: cleanup was printed")Wrap the yield in try/finally whenever the cleanup must run no matter what.
Yielding a value, or nothing
A bare yield is fine when the caller does not need a value. Then you write with manager(): without as. Yield something when the caller needs a handle, such as an open resource or a path.
A generator-based manager must yield exactly once. If it yields zero times, or twice, contextmanager raises a RuntimeError.
Using it as a decorator
Managers made with @contextmanager also work as function decorators. The manager is entered before each call and exited after it.
from contextlib import contextmanager
@contextmanager
def announce(label):
print(f"start {label}")
try:
yield
finally:
print(f"end {label}")
@announce("job")
def run():
print("working")
run()
run()Each call to run() prints the start line, the work line, and the end line. This works because the object returned by @contextmanager supports it. It re-creates the generator for every call.
Class or generator?
| Situation | Better choice |
|---|---|
| Short setup and cleanup, no state to keep | `@contextmanager` |
| Needs methods or attributes the caller reads afterward | Class |
| Needs to inspect or suppress exceptions in detail | Either, but a class is more explicit |
| Must be reusable or reentrant | Class, designed for it |
The next chapter covers how exceptions behave inside the generator in more detail.
Exercise
Write a context manager timer_label(label) with @contextmanager that prints "start <label>" before the body and "end <label>" after it, even if the body raises. Which keyword must wrap the yield, and why?
Show answer
Use try/finally around the yield: from contextlib import contextmanager @contextmanager def timer_label(label): print(f"start {label}") try: yield finally: print(f"end {label}") If the body raises, the exception is thrown into the generator at the yield line. Without finally, the code after yield would be skipped, and "end" would never print.