Sub topic 6
Writing a context manager with @contextmanager
Writing __enter__ and __exit__ as a class works, but it is a lot of ceremony for a short piece of setup and cleanup. The contextlib.contextmanager decorator lets you write the same thing as a single generator function. This chapter covers how that works, what it does with exceptions, and where it differs from a class.
This chapter assumes you know how to write a class-based context manager with __enter__ and __exit__, and how __exit__ receives exception information. It also assumes you are comfortable with generators and the yield keyword, and with basic decorators.
The idea: one yield splits setup from cleanup
A generator function pauses at each yield and resumes later. A context manager has the same shape: run some setup, hand control to the body of the with block, then run cleanup. The decorator maps these steps onto each other.
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())Read the function in three parts:
- Everything before
yieldis the setup. It runs when thewithstatement starts, in place of__enter__. - The value after
yieldis what theasclause receives. If you write a bareyield,asreceivesNone. - Everything after
yieldis the cleanup. It runs when thewithblock ends, in place of__exit__.
Here the finally block restores the previous directory even if the body of the with raises an exception. The next sections explain why that works.
What the decorator does
Calling a function decorated with @contextmanager does not run any of its code. It returns an object that implements __enter__ and __exit__, wrapped around the generator. The object is an instance of an internal class in contextlib, and it behaves like this:
__enter__callsnext()on the generator. The generator runs up to theyield, and the yielded value is returned from__enter__.__exit__with no exception callsnext()again. The generator runs to its end and raisesStopIteration, which the wrapper expects. If the generator yields a second time, the wrapper raisesRuntimeError("generator didn't stop").__exit__with an exception callsgenerator.throw()with that exception. The exception appears inside the generator, at the line of theyield.
The third case is the important one. Because the exception is raised at the yield, you can catch it with an ordinary try statement around the yield.
Why try/finally around the yield matters
The most common mistake with @contextmanager is writing cleanup after the yield without a finally.
from contextlib import contextmanager
@contextmanager
def broken_manager():
print("setup")
yield
print("cleanup") # skipped if the body raises
try:
with broken_manager():
raise ValueError("boom")
except ValueError:
print("caught")This prints setup and then caught. It never prints cleanup. The exception is thrown into the generator at the yield, and nothing catches it there, so it leaves the generator immediately and the line after yield never runs.
The fix is to wrap the yield in try/finally:
from contextlib import contextmanager
@contextmanager
def safe_manager():
print("setup")
try:
yield
finally:
print("cleanup") # always runs
try:
with safe_manager():
raise ValueError("boom")
except ValueError:
print("caught")This prints setup, cleanup, caught, in that order. The exception still propagates to the caller after the cleanup runs.
Passing a value to the as clause
The yielded value can be anything: a file, a connection, a path, a helper object, or a plain number. A common pattern is to open a resource, yield it, and close it in finally.
from contextlib import contextmanager
@contextmanager
def opened(path, mode="r"):
f = open(path, mode)
try:
yield f
finally:
f.close()
with opened("data.txt", "w") as f:
f.write("hello")If acquiring the resource can itself fail, keep the acquisition outside the try. Here, if open raises, there is no file to close, and the exception goes straight to the caller. Putting open inside the try would make finally refer to a variable that was never assigned.
Accepting arguments
A decorated function is an ordinary function, so it takes arguments as usual. Each call creates a new manager object with its own generator.
import time
from contextlib import contextmanager
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.4f} seconds")
with timer("sum"):
sum(range(1_000_000))The elapsed time is printed even when the body raises, because the print is in finally.
To let the caller read the result after the block, yield a mutable object and fill it in during cleanup:
import time
from contextlib import contextmanager
@contextmanager
def timer():
result = {}
start = time.perf_counter()
try:
yield result
finally:
result["elapsed"] = time.perf_counter() - start
with timer() as t:
sum(range(1_000_000))
print(f"{t['elapsed']:.4f} seconds")Comparing the class and generator styles
Both styles produce the same behavior for the with statement. They differ in how much you write and in how they handle exceptions.
| Aspect | Class with `__enter__`/`__exit__` | `@contextmanager` generator |
|---|---|---|
| Amount of code | More: a class and two methods | Less: one function |
| State between setup and cleanup | Stored on `self` | Held in local variables |
| Cleanup on exception | `__exit__` always runs | Needs `try`/`finally` around `yield` |
| Suppressing an exception | Return a true value from `__exit__` | Catch it with `except` and do not re-raise |
| Reuse of one object | Possible if you design for it | One use only: the generator is exhausted afterward |
| Usable as a decorator | Only if it inherits `ContextDecorator` | Yes, automatically |
The last row is worth a note. Objects produced by @contextmanager inherit from ContextDecorator, so you can apply them to a function with the @ syntax. The manager's setup and cleanup then wrap each call. You cannot use the yielded value in that form, because there is no as clause.
from contextlib import contextmanager
@contextmanager
def announce(name):
print(f"start {name}")
try:
yield
finally:
print(f"end {name}")
@announce("job")
def job():
print("working")
job()
job()Each call to job() prints the start line, the work line, and the end line. The decorator form recreates the generator for each call, so repeated calls are safe.
Single use
A manager object returned by a @contextmanager function wraps one generator. Once the with block ends, that generator is finished, and the same object cannot be entered again.
from contextlib import contextmanager
@contextmanager
def once():
yield "value"
manager = once()
with manager as v:
print(v)
try:
with manager as v:
print(v)
except RuntimeError as error:
print("second use failed:", error)The second with raises RuntimeError with the message generator didn't yield. The fix is to call once() again each time you need a manager. Chapter material on reuse and reentrancy covers this in more detail.
Exceptions: a preview of what the next chapter covers
You have already seen that the body's exception is thrown into the generator. Three outcomes are possible when it arrives:
- The generator does not catch it. It propagates out of the generator, and the wrapper lets it continue to the caller. This is the case for
try/finallywith noexcept. - The generator catches it and finishes normally. The wrapper treats that as suppression, and the
withstatement swallows the exception. - The generator catches it and raises a different exception. The new exception replaces the original one, and Python links them through
__context__or__cause__.
This means a bare except around the yield hides errors by accident:
from contextlib import contextmanager
@contextmanager
def swallows_everything():
try:
yield
except Exception:
print("something went wrong")
with swallows_everything():
raise ValueError("lost")
print("this line runs, and the error is gone")The ValueError is caught inside the generator, the generator ends, and the wrapper reports that the exception was handled. If you want to log and still let the error continue, re-raise it with a bare raise:
from contextlib import contextmanager
@contextmanager
def logs_errors():
try:
yield
except Exception as error:
print("logging:", error)
raiseThe details of handling exceptions around the yield are the subject of the next chapter in this tutorial.
Common mistakes
- Cleanup without
finally. Covered above. If the cleanup must always run, put it infinally. - Two yields. A generator that can reach a second
yieldraisesRuntimeError("generator didn't stop"). Each path through the function must yield exactly once. A manager that yields inside anifand sometimes skips theyieldfails withRuntimeError("generator didn't yield"). - Forgetting the decorator. Without
@contextmanager, the function returns a plain generator, andwithraisesTypeErrorbecause the object lacks__enter__. On Python 3.11 and later the message says the object does not support the context manager protocol. - Using
returnto produce the value. The value forasmust be yielded. Areturn valuein a generator does not reach theasclause. - Calling the function without parentheses. Write
with timer():, notwith timer:. The decorated function must be called to build the manager.
Exercises
Exercise
What is the bug in this manager, and how do you fix it? The goal is that "released" is printed even if the body raises. from contextlib import contextmanager @contextmanager def lock(): print("acquired") yield print("released")
Show answer
The code after yield runs only when the body finishes normally. If the body raises, the exception is thrown into the generator at the yield and leaves it, so "released" is never printed. Wrap the yield in try/finally:
@contextmanager
def lock():
print("acquired")
try:
yield
finally:
print("released")
Exercise
Write a @contextmanager function named temporary_value(obj, name, value) that sets the attribute name on obj to value for the duration of the with block, then restores the original value, even if the body raises. Assume the attribute already exists.
Show answer
from contextlib import contextmanager @contextmanager def temporary_value(obj, name, value): original = getattr(obj, name) setattr(obj, name, value) try: yield obj finally: setattr(obj, name, original)
Exercise
A generator-based manager wraps its yield in try/except Exception and prints a message in the except block, with no raise. What happens to an exception raised in the with body, and what single change makes the exception reach the caller after the message is printed?
Show answer
The exception is caught inside the generator, which then ends normally, so the with statement treats the exception as handled and swallows it. Adding a bare raise at the end of the except block re-raises the exception so it propagates to the caller.