ZetCode

Python context managers

last modified November 29, 2026 Python 3.15

In this article we show how to write context managers and how to use the tools of the contextlib module.

A context manager is an object that sets something up before a block of code and tears it down afterwards. The with statement drives it: it calls the manager's __enter__ method before the block and its __exit__ method after the block, whether the block finishes normally, returns, breaks out of a loop, or raises an exception. Files, locks, database transactions, and temporary changes of settings are typical uses.

The basic use of the with statement is shown in Python with keyword. Here we look at how context managers work and how to build our own.

The protocol

Any object with the __enter__ and __exit__ methods is a context manager. The value bound by the as clause is the return value of __enter__, not the manager itself.

protocol.py
class Tracer:

    def __enter__(self):
        print("enter")
        return "the as value"

    def __exit__(self, exc_type, exc, tb):
        print("exit")


with Tracer() as value:
    print("body:", value)

print("after the with statement")

The with statement first calls __enter__, binds its result to value, runs the body, and then calls __exit__. Many managers, such as file objects, return self from __enter__; this one returns a string to show that the two can differ.

$ python protocol.py
enter
body: the as value
exit
after the with statement

Exceptions in __exit__

The __exit__ method receives three arguments: the exception type, the exception object, and the traceback. If the block finished normally, all three are None. If __exit__ returns a true value, the exception is suppressed; otherwise it continues after __exit__ returns.

exceptions_exit.py
class Guard:

    def __init__(self, swallow):
        self.swallow = swallow

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        print(f"exit: {exc_type.__name__ if exc_type else None}: {exc}")
        return self.swallow


with Guard(swallow=True):
    print(1 / 0)
print("the error was suppressed")

try:
    with Guard(swallow=False):
        int("ten")
except ValueError as e:
    print("caught outside:", e)

In the first with statement, the division by zero reaches __exit__, which returns True. The exception is discarded and the program continues after the block. In the second, the manager returns False, so the ValueError propagates and the outer try statement catches it. A method without a return statement returns None, which also lets the exception through; suppressing must always be an explicit decision.

$ python exceptions_exit.py
exit: ZeroDivisionError: division by zero
the error was suppressed
exit: ValueError: invalid literal for int() with base 10: 'ten'
caught outside: invalid literal for int() with base 10: 'ten'

A reusable timer

A context manager can store results on itself. Because the with statement calls __enter__ each time, the same object can be used for several blocks.

timer.py
import time


class Timer:

    def __enter__(self):
        self.start = time.perf_counter()
        self.elapsed = None
        return self

    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self.start


timer = Timer()

with timer:
    total = sum(range(5_000_000))
print(f"sum took {timer.elapsed:.2f} s")

with timer:
    time.sleep(0.25)
print(f"sleep took {timer.elapsed:.2f} s")

The __enter__ method records the start time with the high-resolution perf_counter clock, and __exit__ stores the elapsed time. The timer object is created once and reused for two measurements; after each block, the result is available in its elapsed attribute. The exact times differ from run to run.

$ python timer.py
sum took 0.04 s
sleep took 0.25 s

A nested context manager

Some managers can be entered again while they are already active. They must keep track of the nesting so that each exit undoes exactly one enter.

indenter.py
class Indenter:

    def __init__(self):
        self.level = 0

    def __enter__(self):
        self.level += 1
        return self

    def __exit__(self, exc_type, exc, tb):
        self.level -= 1

    def print(self, text):
        print("    " * self.level + text)


out = Indenter()

with out:
    out.print("chapter 1")
    with out:
        out.print("section 1.1")
        out.print("section 1.2")
    out.print("chapter 2")

Each with out increases the indentation level and each exit decreases it again. The nested block prints the sections one level deeper, and after it ends, chapter 2 returns to the outer level. The same object is entered twice at the same time, which works because the manager counts levels instead of storing a single state.

$ python indenter.py
    chapter 1
        section 1.1
        section 1.2
    chapter 2

Generator-based context managers

Writing a class with two special methods is verbose for simple cases. The contextmanager decorator from contextlib turns a generator function into a context manager. The code before yield runs on entry, the code after it on exit.

generator_cm.py
from contextlib import contextmanager


@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")


with tag("ul"):
    with tag("li"):
        print("tea")
    with tag("li"):
        print("coffee")

The tag function prints an opening tag, yields control to the body of the with statement, and prints the closing tag when the body is done. The nested statements produce a correctly nested list.

$ python generator_cm.py
<ul>
<li>
tea
</li>
<li>
coffee
</li>
</ul>

Cleanup with try/finally

The previous tag function has a flaw. If the body raises an exception, the exception is raised inside the generator at the yield, and the code after the yield never runs. Cleanup code in a generator-based manager belongs in a finally clause.

generator_finally.py
from contextlib import contextmanager


@contextmanager
def tag(name, broken):
    print(f"<{name}>")
    if broken:
        yield
        print(f"</{name}>")
    else:
        try:
            yield
        finally:
            print(f"</{name}>")


for broken in (True, False):
    try:
        with tag("p", broken):
            raise RuntimeError("render failed")
    except RuntimeError as e:
        print("error:", e, "| broken" if broken else "| fixed")

Both versions of the function are combined in one generator to compare them. In the broken version, the exception skips the closing tag and the output is left with an unclosed <p>. In the fixed version, the finally clause prints the closing tag before the exception continues to the caller.

$ python generator_finally.py
<p>
error: render failed | broken
<p>
</p>
error: render failed | fixed

Yielding a value and handling errors

The value of the yield expression becomes the target of the as clause. Wrapping the yield in try/except lets the manager react to errors in the body; an exception handled there is suppressed.

generator_value.py
from contextlib import contextmanager


@contextmanager
def transaction(store):
    work = dict(store)
    try:
        yield work
    except ValueError as e:
        print("rolled back:", e)
    else:
        store.update(work)
        print("committed")


stock = {"apples": 10, "pears": 4}

with transaction(stock) as tx:
    tx["apples"] -= 3

with transaction(stock) as tx:
    tx["pears"] -= 2
    if tx["pears"] < 5:
        raise ValueError("pears below minimum")

print(stock)

The transaction manager gives the body a copy of the stock. If the body succeeds, the else clause writes the changes back. If the body raises ValueError, the copy is discarded and the original data stays untouched. The second transaction is rolled back, so the final stock contains only the change from the first one.

$ python generator_value.py
committed
rolled back: pears below minimum
{'apples': 7, 'pears': 4}

Ready-made managers in contextlib

The contextlib module contains several small managers for common tasks. The suppress manager ignores the listed exceptions, redirect_stdout sends printed output to another file-like object, and nullcontext is a manager that does nothing.

contextlib_tools.py
import io
from contextlib import nullcontext, redirect_stdout, suppress

values = {"a": 1}

with suppress(KeyError):
    print(values["b"])
print("missing key ignored")

buffer = io.StringIO()
with redirect_stdout(buffer):
    print("captured line")
print("buffer holds:", repr(buffer.getvalue()))

for quiet in (True, False):
    cm = redirect_stdout(io.StringIO()) if quiet else nullcontext()
    with cm:
        print(f"progress (quiet={quiet}): 100%")

The missing key raises KeyError; suppress catches it and the block ends silently. The output of the second block goes into a StringIO buffer instead of the terminal. In the loop, nullcontext stands in when no redirection is needed, so a single with statement handles both cases. Other managers in the module include closing, chdir, which temporarily changes the working directory, and asynccontextmanager for the async with statement.

$ python contextlib_tools.py
missing key ignored
buffer holds: 'captured line\n'
progress (quiet=False): 100%

A variable number of managers

A with statement lists its managers in the source code. When the number of resources is known only at runtime, ExitStack collects them dynamically and exits them all at the end of the block.

exit_stack.py
from contextlib import ExitStack


class Connection:

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("open", self.name)
        return self

    def __exit__(self, exc_type, exc, tb):
        print("close", self.name)


servers = ["alpha", "beta", "gamma"]

with ExitStack() as stack:
    connections = [stack.enter_context(Connection(s)) for s in servers]
    stack.callback(print, "all connections released")
    print("using", len(connections), "connections")

The enter_context method enters a manager and registers its exit. The callback method registers a plain function call. At the end of the block, the stack runs everything in reverse order: the callback first, then the connections from the last to the first. If entering one of the managers failed, the ones already entered would still be closed.

$ python exit_stack.py
open alpha
open beta
open gamma
using 3 connections
all connections released
close gamma
close beta
close alpha

Source

contextlib documentation, With statement context managers, PEP 343 – The with statement

In this article we have looked at how the with statement calls __enter__ and __exit__, how __exit__ suppresses exceptions, and how to write reusable and nested context managers as classes and as generators. We have also used suppress, redirect_stdout, nullcontext, and ExitStack from the contextlib module. See also Python with keyword, Python generators, and Python magic methods.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.