Sub topic 13
Replacing try/finally with context managers
This chapter assumes you can write try/except/finally blocks, know that finally runs on every exit path, and can read a basic class definition with methods such as __init__. Here you will see how the with statement packages the same cleanup guarantee into a reusable object.
The problem with repeated try/finally
Any resource that must be released needs the same shape of code: acquire it, then use it inside try, then release it in finally.
f = open("notes.txt")
try:
first_line = f.readline()
finally:
f.close()This is correct. The problem is that every caller must remember to write it, and the acquire and release steps sit far apart from each other. A forgotten finally leaks the resource only on the failure path, which is the path you test least.
A context manager moves the acquire and release logic into one object. The caller then writes:
with open("notes.txt") as f:
first_line = f.readline()The file is closed when the block ends, whether it ends normally, through return, break, or continue, or through an exception.
The context manager protocol
An object can be used in a with statement if it has two methods:
__enter__(self)runs when the block starts. Its return value is bound to the name afteras.__exit__(self, exc_type, exc_value, traceback)runs when the block ends. If the block finished without an exception, all three arguments areNone. Otherwise they describe the exception.
The return value of __exit__ matters only when an exception occurred. If it returns a true value, the exception is suppressed and execution continues after the with block. If it returns False or None, the exception continues to propagate. Most context managers should return None (or False) so they never hide errors.
Writing a context manager as a class
This example restores a list to its earlier contents if the block fails:
class Transaction:
def __init__(self, items):
self.items = items
self.snapshot = None
def __enter__(self):
self.snapshot = list(self.items)
return self.items
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
self.items[:] = self.snapshot
print("rolled back")
return False
data = [1, 2]
try:
with Transaction(data) as d:
d.append(3)
raise RuntimeError("boom")
except RuntimeError:
print(data)This prints rolled back and then [1, 2]. The rollback ran inside __exit__, and because __exit__ returned False, the RuntimeError still reached the outer except. The with statement does not replace error handling. It only guarantees the cleanup step.
Writing a context manager with @contextmanager
For simple cases, a class is more code than needed. The contextlib.contextmanager decorator turns a generator function into a context manager. Code before yield is the __enter__ part, the yielded value is bound by as, and code after yield is the __exit__ part.
from contextlib import contextmanager
@contextmanager
def opened(path):
f = open(path)
try:
yield f
finally:
f.close()
with opened("notes.txt") as f:
first_line = f.readline()The try/finally has not disappeared. It now lives in one place, inside the helper, instead of at every call site.
Why the try/finally inside the generator matters
When the body of the with block raises, the decorator throws that exception into the generator at the yield line. If the cleanup code is written after the yield with no finally, the exception skips it:
from contextlib import contextmanager
@contextmanager
def broken_timer(label):
print(f"start {label}")
yield
print(f"end {label}") # skipped if the body raises
@contextmanager
def timer(label):
print(f"start {label}")
try:
yield
finally:
print(f"end {label}") # always runs
try:
with broken_timer("a"):
raise ValueError
except ValueError:
pass
try:
with timer("b"):
raise ValueError
except ValueError:
passThe output is start a, start b, end b. The first manager never prints end a. This is the most common mistake with @contextmanager, so treat try/finally around yield as the default shape.
Handling or suppressing errors in a generator
You can also catch the exception around the yield. If the generator catches it and finishes normally, the exception is suppressed. If it lets it escape, the exception propagates.
from contextlib import contextmanager
@contextmanager
def ignore_missing(path):
try:
yield
except FileNotFoundError:
print(f"{path} not found, continuing")
with ignore_missing("old.log"):
open("old.log").close()
print("after block")If old.log does not exist, the program prints the message and then after block. Suppression like this should be narrow: name one exception type, as above, never Exception.
Ready-made context managers
The standard library already covers common cases, so check before writing your own.
| Tool | Purpose |
|---|---|
| `open()` | Closes the file on exit |
| `threading.Lock` | Acquires on enter and releases on exit |
| `contextlib.suppress(*types)` | Ignores the listed exception types |
| `contextlib.closing(obj)` | Calls `obj.close()` on exit for objects that lack `__exit__` |
| `contextlib.ExitStack` | Manages a variable number of context managers |
suppress replaces a common four-line try/except/pass pattern:
import os
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("temp.txt")To use several managers in one statement, list them with commas. Each is entered left to right and exited in reverse order:
with open("in.txt") as src, open("out.txt", "w") as dst:
dst.write(src.read())Python 3.10 and later also accept parentheses around the list, which lets you split it over several lines. When the number of managers is not known in advance, ExitStack lets you enter them in a loop and still unwinds them correctly.
Edge cases and gotchas
- Exit order. Managers exit in reverse of the order they entered, like nested
try/finallyblocks. If__exit__for the inner one raises, the outer one still runs. - Errors in
__exit__. If__exit__raises while another exception is already active, the new exception replaces it. Python chains the original as__context__, so you can still see it in the traceback. - Errors in
__enter__. If__enter__raises, the body does not run and__exit__is not called. Anything__enter__acquired before failing must be cleaned up inside__enter__itself. - Single use. A manager made by
@contextmanagercan be used once. Calling the decorated function again gives you a fresh one. - One yield. The generator must yield exactly once. Zero or two yields raise
RuntimeError. - Returning true from
__exit__. This hides every exception type, including ones you did not expect. Return it only after checkingexc_typeagainst the specific types you intend to suppress.
When to choose each form
Use try/finally directly when the cleanup is used once and is short. Use @contextmanager when the same acquire and release pair appears in several places and needs no state beyond local variables. Use a class when the manager needs to be reusable, hold configuration, or expose methods to the body, or when you need to inspect the exception type in __exit__ and decide whether to suppress it.
Exercise
What does this program print, and why? from contextlib import contextmanager @contextmanager def guard(): print("enter") try: yield finally: print("cleanup") try: with guard(): print("body") raise KeyError("x") print("unreachable") except KeyError: print("caught")
Show answer
It prints enter, body, cleanup, caught, each on its own line. The KeyError is thrown into the generator at the yield, the finally block prints cleanup, and since the generator does not catch the error it propagates out of the with statement to the outer except, which prints caught. The line after raise never runs.
Exercise
A class-based context manager has an _exit_ method that ends with "return True" and does no checks. What is the effect on a ValueError raised in the with body, and how would you restrict it to only KeyError?
Show answer
Returning True suppresses the ValueError, so the code after the with block runs as though nothing failed. To restrict it, check the exception type and return True only for the intended case, for example "return exctype is not None and issubclass(exctype, KeyError)". For any other outcome, including no exception, _exit_ then returns False and errors propagate.