Skip to content

Lesson 26 of 52Pythonic Python

Context Managers

Guarantee cleanup with the with statement, and write your own context managers as classes or generators.

20 min read0/6 questions

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:

Python
with open("notes.txt", "w") as f: f.write("hello\n") print("inside, closed?", f.closed) print("after, closed?", f.closed)
Output
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 after as.
  • __exit__(self, exc_type, exc, tb) runs at the end. If the block raised, the three arguments describe the exception; otherwise they are all None. If __exit__ returns True, the exception is suppressed; otherwise it continues upwards.
with Resource() as r: body
with statementResourceyour block__enter__()returns rrun bodydone / raised__exit__(type, exc, tb)

Set-up happens first: open the file, take the lock, start the timer.

1/5
Python
class Announce: def __init__(self, name): self.name = name def __enter__(self): print(f"enter {self.name}") return self def __exit__(self, exc_type, exc, tb): print(f"exit {self.name}, error: {exc_type.__name__ if exc_type else None}") return False # do not suppress with Announce("A") as a: print(" body using", a.name) try: with Announce("B"): raise ValueError("boom")except ValueError: print("the error still reached us")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.
Quick check
A context manager's __exit__ returns True, and the block raises KeyError. What happens?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from contextlib import contextmanagerimport time @contextmanagerdef timer(label): start = time.perf_counter() try: yield # the with-block runs here finally: ms = (time.perf_counter() - start) * 1000 print(f"{label}: {ms:.2f} ms") with timer("sum"): total = sum(range(500_000))print(total)
Output
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.

Python
from contextlib import contextmanager settings = {"debug": False} @contextmanagerdef override(key, value): old = settings[key] settings[key] = value try: yield settings finally: settings[key] = old # restored even if the block raises with override("debug", True): print("inside:", settings)print("after:", settings)
Output
Press Run (⌘ Enter) to see what happens.
Put it in order4 steps

In a @contextmanager generator, put these in the order they run.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

Python
class Transaction: def __init__(self, log): self.log = log def __enter__(self): self.log.append("BEGIN") return self def __exit__(self, exc_type, exc, tb): if exc_type is None: self.log.append("COMMIT") else: self.log.append(f"ROLLBACK ({exc_type.__name__}: {exc})") return False # never hide the caller's error class LeakyTransaction(Transaction): def __exit__(self, exc_type, exc, tb): super().__exit__(exc_type, exc, tb) return self.log # oops: a non-empty list is truthy log = []try: with Transaction(log): raise ValueError("negative amount")except ValueError: log.append("caller saw the error") with LeakyTransaction(log): raise ValueError("card declined")log.append("caller carried on as if it worked") print(*log, sep="\n")
Output
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 False or None unless suppression is the whole point of the class, like suppress. 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.
Predict the outputPython

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__)
Need a nudge? Hints walk you through it.

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:

Python
from contextlib import contextmanager @contextmanagerdef transaction(log): log.append("BEGIN") try: yield except Exception as e: log.append(f"ROLLBACK ({e})") raise # without this line the error vanishes else: log.append("COMMIT") log = []for amount in (10, -5): try: with transaction(log): if amount < 0: raise ValueError("negative amount") log.append(f" insert {amount}") except ValueError as e: log.append(f"caller saw: {e}")print(*log, sep="\n")
Output
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 managerWhat 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
Python
import threadingfrom contextlib import suppressimport os lock = threading.Lock()with lock: print("locked:", lock.locked())print("released:", not lock.locked()) with suppress(FileNotFoundError): os.remove("does-not-exist.txt")print("no crash")
Output
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:

Python
import io, os, tempfile, threadingfrom contextlib import chdir, closing, nullcontext, redirect_stdout # closing(): for objects with .close() but no with-supportclass LegacyConnection: def query(self, sql): return [("ada",), ("sam",)] def close(self): print("connection closed") with closing(LegacyConnection()) as conn: print(conn.query("SELECT name FROM users")) # chdir(): work in another directory, always come back (3.11+)start = os.getcwd()with tempfile.TemporaryDirectory() as tmp: with chdir(tmp): with open("out.txt", "w") as f: f.write("x") print("inside tmp:", sorted(os.listdir("."))) print("back home:", os.getcwd() == start) # redirect_stdout(): capture print output from code you do not controlbuffer = io.StringIO()with redirect_stdout(buffer): print("noisy library output")print("captured:", repr(buffer.getvalue())) # nullcontext(): "maybe" use a context manager without duplicating codedef save(record, lock=None): with lock if lock is not None else nullcontext(): return f"saved {record}" print(save("a"), "|", save("b", threading.Lock()))
Output
Press Run (⌘ Enter) to see what happens.
  • closing(obj) calls obj.close() at the end. Use it for older objects (some database drivers, urllib responses in old code) that have a close method but no __enter__.
  • chdir(path) (3.11) changes the working directory and restores it. Handy in build scripts and tests.
  • redirect_stdout(target) sends print output to any file-like object. Its partner redirect_stderr does the same for errors.
  • nullcontext(value) does nothing and hands back value. It removes the "duplicate the block with and without the with" pattern when a lock, transaction or file is optional. A common shape is with open(path) if path else nullcontext(sys.stdin) as f: for a CLI that reads a file or standard input.
Match the pairs0/5 matched

Match each job to the contextlib tool that does it.

Choose an item, then its match on the other side.

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.

Python
from contextlib import ContextDecorator, contextmanagerimport time @contextmanagerdef timer(label): start = time.perf_counter() try: yield finally: print(f"{label}: {(time.perf_counter() - start) * 1000:.1f} ms") with timer("block"): # as a with statement sum(range(100_000)) @timer("whole function") # the same object as a decoratordef build_report(): return sum(range(200_000)) build_report()build_report() # fresh context manager each call class audited(ContextDecorator): def __init__(self, action): self.action = action def __enter__(self): print(f"audit: start {self.action}") return self def __exit__(self, exc_type, exc, tb): status = "failed" if exc_type else "ok" print(f"audit: {self.action} {status}") return False @audited("delete user")def delete_user(user_id): if user_id == 0: raise ValueError("cannot delete the system user") print(f" deleting {user_id}") delete_user(7)try: delete_user(0)except ValueError as e: print("error:", e)
Output
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.

Python
from contextlib import ExitStack names = ["a.txt", "b.txt", "c.txt"]with ExitStack() as stack: files = [stack.enter_context(open(n, "w")) for n in names] for f in files: f.write("x") print("open:", [not f.closed for f in files])print("closed:", [f.closed for f in files])
Output
Press Run (⌘ Enter) to see what happens.
Quick check
with A() as a, B() as b: finishes. In which order do the __exit__ methods run?
Need a nudge? A hint rules out a wrong answer.

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 (a close() 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. The with block 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.

Python
from contextlib import ExitStack class Resource: def __init__(self, name, fail=False): if fail: raise ConnectionError(f"{name} unavailable") self.name = name print(f"open {name}") def close(self): print(f"close {self.name}") class Pipeline: """Owns several resources; either gets all of them or none.""" def __init__(self, cache_down=False): with ExitStack() as stack: self.db = Resource("db") stack.callback(self.db.close) self.queue = Resource("queue") stack.callback(self.queue.close) self.cache = Resource("cache", fail=cache_down) stack.callback(self.cache.close) self._stack = stack.pop_all() # success: keep everything open def close(self): self._stack.close() # closes in reverse order p = Pipeline()print("working...")p.close() print("---")try: Pipeline(cache_down=True)except ConnectionError as e: print("constructor failed:", e)
Output
Press Run (⌘ Enter) to see what happens.
Pipeline(cache_down=True): the ExitStack unwinds
  1. cache: Resource("cache")raises ConnectionError, never registered
  2. callback: queue.closeregistered second
  3. callback: db.closeregistered first

db opens and its close is pushed onto the stack.

1/5

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__.

clients.py
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.)

ChallengeEasy

A Timer context manager

Write a class Timer that works with with:

  • __enter__ records the start time with time.perf_counter() and returns the timer itself.
  • __exit__ sets the attribute elapsed to the number of seconds the block took (a float).
  • Exceptions from the block must not be suppressed, and elapsed must still be set when one happens.
  • Before the block finishes, elapsed is None.
with Timer() as t:
    total = sum(range(1_000_000))
print(t.elapsed)   # e.g. 0.021
Python
import time class Timer: def __init__(self) -> None: pass # Add __enter__ and __exit__.
ChallengeMedium

Temporarily 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 key existed, its old value comes back;
  • if key did 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}
Python
from contextlib import contextmanager @contextmanagerdef override(config: dict, key: str, value): # Save the old state, set the new value, yield, and restore in finally. yield config
Key terms
context manager
An object with __enter__ and __exit__, used in a with statement to guarantee set-up and cleanup.
__exit__
Called when the with block ends, with any exception's type, value and traceback. Truthy return suppresses it.
@contextmanager
Turns a generator into a context manager: before yield is 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.