Lesson 26 of 52Pythonic Python
Context Managers
Guarantee cleanup with the with statement, and write your own context managers as classes or generators.
Files must be closed, locks released, database transactions committed or rolled back, temporary settings restored. Forgetting cleanup leaks resources, and the bugs only appear under load, at 3 a.m. Python's with statement makes cleanup automatic and guaranteed, even when an exception flies through. Every database library, HTTP client and test framework you will use relies on it.
The problem with solves
Here is file handling without with:
f = open("data.txt")
data = f.read() # if this raises, close() never runs
f.close()To make it safe you need try/finally. That is correct, but noisy, and easy to forget:
f = open("data.txt")
try:
data = f.read()
finally:
f.close()The with statement packages exactly that pattern:
Press Run (⌘ Enter) to see what happens.The file is closed the moment the indented block ends, however it ends: normally, with return, with break, or with an exception.
The protocol: __enter__ and __exit__
An object you can use in a with statement is a context manager. It has two dunder methods:
__enter__(self)runs at the start. Whatever it returns is bound to the name afteras.__exit__(self, exc_type, exc, tb)runs at the end. If the block raised, the three arguments describe the exception; otherwise they are allNone. If__exit__returnsTrue, the exception is suppressed; otherwise it continues upwards.
Set-up happens first: open the file, take the lock, start the timer.
Press Run (⌘ Enter) to see what happens.What does this print?
class CM:
def __enter__(self):
print("in")
return 42
def __exit__(self, *args):
print("out")
with CM() as value:
print(value)__exit__ returns True, and the block raises KeyError. What happens?The easy way: contextlib.contextmanager
Writing a class is verbose for simple cases. The @contextmanager decorator turns a generator into a context manager. Code before yield is the set-up, the yielded value is what as receives, and code after yield is the cleanup. Wrap the yield in try/finally so the cleanup runs even on errors.
Press Run (⌘ Enter) to see what happens.Here is a very common real-world pattern: temporarily change something and always put it back. Tests do this constantly.
Press Run (⌘ Enter) to see what happens.In a @contextmanager generator, put these in the order they run.
- Tap the steps below in the right order.
Exceptions and __exit__: the rules that bite
__exit__ receives three arguments when the block raises: the exception class, the exception instance, and the traceback. When the block finishes normally all three are None. A transaction manager is the textbook use: commit on success, roll back on failure, and let the error carry on so the caller knows.
The danger is the return value. Python treats any truthy value returned from __exit__ as "I handled it", not just True. A method that returns something by accident can silently eat every error in the block:
Press Run (⌘ Enter) to see what happens.The second block raised, rolled back, and then the program carried on as if the payment succeeded. Nothing was printed, nothing was logged. The rules that keep you safe:
- Return
FalseorNoneunless suppression is the whole point of the class, likesuppress. Do not return the result of another call from__exit__. - Do not re-raise the exception yourself inside
__exit__. Just return a falsy value and Python re-raises it with the original traceback intact. - If
__exit__itself raises, the new exception replaces the one from the block. The original is not lost (it is attached as__context__and shown in the traceback as "During handling of the above exception, another exception occurred"), but callers now catch the wrong type. Keep cleanup code simple, and if a cleanup step can fail, catch and log that failure rather than letting it mask the real error.
What does this print?
class CM:
def __enter__(self):
return self
def __exit__(self, *exc_info):
raise RuntimeError("cleanup failed")
try:
with CM():
raise ValueError("real problem")
except Exception as e:
print(type(e).__name__, "|", type(e.__context__).__name__)The same rules for @contextmanager
In a generator-based context manager, an exception in the block is thrown into the generator at the yield. Whatever the generator does with it is what happens:
Press Run (⌘ Enter) to see what happens.If you catch the exception around yield and do not raise it again, it is suppressed, exactly like returning True from __exit__. try/finally around the yield is always safe, because finally cleans up and lets the error continue. Use except only when the cleanup differs between success and failure, as it does for commit and rollback, and always end it with a bare raise. Also, the generator must yield exactly once: a second yield gives RuntimeError: generator didn't stop.
Context managers you will use every day
| Context manager | What it guarantees |
|---|---|
open(path) | The file is closed |
threading.Lock() | The lock is released, so other threads are not stuck forever |
sqlite3.connect(...) (and most DB sessions) | The transaction is committed on success, rolled back on error |
contextlib.suppress(FileNotFoundError) | Only that exception is silently ignored |
tempfile.TemporaryDirectory() | The temporary folder is deleted |
unittest.mock.patch(...) | A patched object is restored after the test |
decimal.localcontext() | Precision settings are restored |
Press Run (⌘ Enter) to see what happens.suppress is the honest way to ignore one specific error. It is much clearer than try: ... except FileNotFoundError: pass, and it cannot accidentally swallow other errors.
The rest of the contextlib toolbox
suppress is one of several small tools in contextlib that save you writing a class. These four turn up constantly in real code:
Press Run (⌘ Enter) to see what happens.closing(obj)callsobj.close()at the end. Use it for older objects (some database drivers,urllibresponses in old code) that have aclosemethod but no__enter__.chdir(path)(3.11) changes the working directory and restores it. Handy in build scripts and tests.redirect_stdout(target)sendsprintoutput to any file-like object. Its partnerredirect_stderrdoes the same for errors.nullcontext(value)does nothing and hands backvalue. It removes the "duplicate the block with and without thewith" pattern when a lock, transaction or file is optional. A common shape iswith open(path) if path else nullcontext(sys.stdin) as f:for a CLI that reads a file or standard input.
Match each job to the contextlib tool that does it.
One object, two uses: ContextDecorator
Sometimes you want the same behaviour around a whole function: time it, audit it, run it inside a transaction. Context managers made with @contextmanager already work as decorators too, because they inherit from contextlib.ContextDecorator. For a class-based one, subclass ContextDecorator yourself.
Press Run (⌘ Enter) to see what happens.Used as a decorator, the whole function body becomes the with block. Two limits: the decorated function cannot see the value __enter__ returns (there is no as), and on an async def function a plain ContextDecorator would only wrap the creation of the coroutine, not its execution. For async functions, use AsyncContextDecorator or @asynccontextmanager, whose objects support this too.
Notice also that a @contextmanager object is single-use: its generator can only run once. The decorator form works because it quietly recreates the context manager on every call. If you store t = timer("x") and use with t: twice, the second time fails with a confusing AttributeError. Class-based managers like audited that reset their state in __enter__ can be reused, and a few, like threading.RLock, are even reentrant: you can enter them again while already inside.
Several at once, and ExitStack
One with can manage several context managers. Python 3.10+ lets you use parentheses to split them over lines. They exit in reverse order, like a stack.
with (
open("input.txt") as src,
open("output.txt", "w") as dst,
):
dst.write(src.read())When you do not know how many you need until runtime (say, opening a list of files), use contextlib.ExitStack. You enter_context each one, and the stack closes them all, in reverse, when the block ends.
Press Run (⌘ Enter) to see what happens.with A() as a, B() as b: finishes. In which order do the __exit__ methods run?ExitStack for dynamic cleanup: callback and pop_all
ExitStack is not only for a variable number of files. It is a general cleanup stack: anything you push onto it gets undone in reverse order when the block ends, whether the block finished or raised. Two methods make it the senior engineer's tool for messy set-up code:
stack.callback(fn, *args)registers any function as a cleanup step, so things that are not context managers (aclose()method, deleting a temp row, stopping a mock server) still get cleaned up.stack.pop_all()moves everything registered so far onto a new stack and empties the current one. Thewithblock then ends without cleaning anything up, and you keep the new stack to close later.
Together they solve a hard problem: a constructor that opens several resources. If the third one fails, the first two must be closed, but if all three succeed they must stay open after __init__ returns.
Press Run (⌘ Enter) to see what happens.db opens and its close is pushed onto the stack.
Without ExitStack, the same guarantee needs nested try blocks that grow with every resource. Test fixtures, CLI tools that open optional outputs, and integration tests that start several fake services all use this pattern.
Async context managers
Async code has its own version: async with, which calls await obj.__aenter__() and await obj.__aexit__(...). You need it whenever set-up or cleanup itself does I/O, such as opening a network connection, acquiring a database connection from a pool or closing an HTTP client's sockets. The rules for exceptions and suppression are exactly the same as for __exit__.
from contextlib import asynccontextmanager, AsyncExitStack
import httpx
@asynccontextmanager
async def api_client(base_url: str):
client = httpx.AsyncClient(base_url=base_url, timeout=10)
try:
yield client
finally:
await client.aclose() # cleanup can await too
async def sync_orders() -> None:
async with api_client("https://api.example.com") as client:
response = await client.get("/orders")
response.raise_for_status()
async def open_many(urls: list[str]) -> None:
async with AsyncExitStack() as stack: # the async ExitStack
clients = [await stack.enter_async_context(api_client(u)) for u in urls]
...You will meet @asynccontextmanager in every FastAPI app: the lifespan function that opens database pools at start-up and closes them at shutdown is one. async with only works inside async def, and a plain with on an async context manager fails with a TypeError telling you to use async with. Async and Await covers the event loop that runs all of this. (Async examples here are shown as static code, because the in-browser runner cannot drive a real event loop.)
A Timer context manager
Write a class Timer that works with with:
__enter__records the start time withtime.perf_counter()and returns the timer itself.__exit__sets the attributeelapsedto the number of seconds the block took (a float).- Exceptions from the block must not be suppressed, and
elapsedmust still be set when one happens. - Before the block finishes,
elapsedisNone.
with Timer() as t:
total = sum(range(1_000_000))
print(t.elapsed) # e.g. 0.021Temporarily override a setting
Write a context manager override(config, key, value) using @contextlib.contextmanager.
Inside the with block, config[key] is value. When the block ends (normally or with an exception), config is restored exactly:
- if
keyexisted, its old value comes back; - if
keydid not exist, it is removed again.
The with statement should give you the config dict: with override(cfg, "debug", True) as c:.
cfg = {"debug": False}
with override(cfg, "debug", True):
cfg["debug"] # True
cfg # {"debug": False}
with override(cfg, "region", "eu"):
cfg["region"] # "eu"
cfg # {"debug": False}- context manager
- An object with
__enter__and__exit__, used in awithstatement to guarantee set-up and cleanup. - __exit__
- Called when the
withblock ends, with any exception's type, value and traceback. Truthy return suppresses it. - @contextmanager
- Turns a generator into a context manager: before
yieldis set-up, after it is cleanup. - suppress
contextlib.suppress(Err)ignores only the listed exception types inside its block.- ExitStack
- Manages a dynamic number of context managers and exits them all in reverse order.