Python

Python Context Managers — with, __enter__, __exit__, and contextlib

Some work comes in pairs: open and close, set up and tear down, acquire and release. A context manager is the object that owns the second half of the pair, and the with statement is what makes sure it runs. This guide shows the working core: a file used with with, a manager you write as a class, what __exit__ receives when the block raises, the one return value that holds an exception in, a manager built from a generator function, several managers on one line, and a stack for a count known only while the program runs.

Written November 12, 2026 · Tested with Python 3.12.3 · 9 min read

By the end of this guide
  • The main program: a file under with
  • A manager you write is a class with two methods
  • exit receives the exception
  • Returning true holds the exception in

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

A context manager is an object that sets something up before a block of code and cleans it up after the block. The with statement drives it: entering the statement runs the setup, leaving the block runs the cleanup, and the cleanup runs even when the block raises an error. Files are the manager most programs meet first, but the pattern fits any paired work, such as a session, a lock, or a temporary setting. You can use a manager that already exists, write one as a class, or build one from a small generator function.

The main program: a file under with

Opening a file returns a context manager. The as name holds the file while the block runs, and leaving the block closes it:

Python
from pathlib import Path

Path("notes.txt").write_text("alpha\nbeta\n", encoding="utf-8")
with open("notes.txt", encoding="utf-8") as f:
    print("inside closed:", f.closed)
    print(f.read(), end="")
print("after closed:", f.closed)

The exact output:

Output
inside closed: False
alpha
beta
after closed: True

Inside the block the file reports itself open, and its content reads as the two lines that were written. After the block the same file reports itself closed, with no close call written anywhere in the program. The with statement made that call at the end of the block. If the reading code had raised an error instead of printing, the close would still have run, because leaving the block for any reason triggers the cleanup half of the pair.

A manager you write is a class with two methods

Any class with an enter method and an exit method is a context manager. The first runs on entry and its return value becomes the as name. The second runs on exit:

Python
class Resource:
    def __enter__(self):
        print("enter")
        self.state = "open"
        return self

    def __exit__(self, exc_type, exc, tb):
        print("exit")
        self.state = "closed"
        return False

with Resource() as r:
    print("inside", r.state)
print("after", r.state)

The exact output:

Output
enter
inside open
exit
after closed

The order is fixed: enter first, then the block, then exit. Returning self from enter is what puts the resource itself behind the as name; a manager may return a different object when the block should work with something narrower than the manager. The False return from exit in this example is the normal choice, and the next two sections show what it decides.

exit receives the exception

When the block raises, exit still runs, and its three arguments describe what happened: the exception type, the exception value, and its traceback. When the block ends cleanly, all three arrive as None. Returning False lets the exception keep spreading after the cleanup:

Python
class Tracked:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        name = exc_type.__name__ if exc_type else None
        print("cleanup saw:", name)
        return False

try:
    with Tracked():
        print("body")
        raise ValueError("bad input")
except ValueError as e:
    print("caught", e)

The exact output:

Output
body
cleanup saw: ValueError
caught bad input

The cleanup line prints before the caught line, which shows the order: the block raises, exit runs and sees the ValueError, then, because it returned False, the same error reaches the except clause outside. This shape is the right default for most managers: do the cleanup, learn what happened if you need to, and let the caller deal with the error.

Returning true holds the exception in

An exit that returns a true value tells the with statement the exception has been handled. The block ends as if no error occurred, and the code after the with line runs:

Python
class IgnoreValueError:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        print("exit saw:", exc_type.__name__)
        return True

with IgnoreValueError():
    print("body")
    raise ValueError("bad input")
print("continued")

The exact output:

Output
body
exit saw: ValueError
continued

No caught line appears, because nothing outside ever sees the error. This is a strong tool, so it fits only a manager whose whole job is to absorb one known error. A manager that returns true for every exception would hide real faults along with the one it meant to hold in, and the program would continue in a state nobody checked.

A manager from a generator function

The contextlib module offers a shorter build for the common case. Decorating a generator function with @contextmanager turns it into a manager factory: the code before the yield is the setup, the yielded value becomes the as name, and the code after the yield is the cleanup:

Python
from contextlib import contextmanager

@contextmanager
def tagged(name):
    print(f"start {name}")
    try:
        yield name.upper()
    finally:
        print(f"end {name}")

with tagged("job") as value:
    print("body", value)

The exact output:

Output
start job
body JOB
end job

The generator yields exactly once. The try and finally around the yield matter: if the block raises, the error is thrown back into the generator at the yield point, and the finally clause is what still runs the cleanup. Wrapping the yield in try and finally is therefore the standard shape, not an extra. Choose this form when the manager is a short pair of setup and teardown steps with no state worth keeping; choose the class form when the manager carries methods or state of its own.

Several managers on one line exit in reverse order

A single with line can hold more than one manager, separated by commas. They enter from left to right and exit from right to left, like nested blocks written on one line:

Python
class Named:
    def __init__(self, name):
        self.name = name

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

    def __exit__(self, exc_type, exc, tb):
        print("exit", self.name)
        return False

with Named("first") as a, Named("second") as b:
    print("body", a.name, b.name)

The exact output:

Output
enter first
enter second
body first second
exit second
exit first

Reverse order on exit is the safe order for paired work: the manager entered last may depend on the one entered first, so it must be torn down while the earlier one is still in place. Writing the pair as two nested with blocks gives the same order; the one-line form is just shorter when the block is small.

ExitStack for a count known only at run time

The comma form needs the managers listed in the source. When the count depends on data, such as one file per name in a list, the contextlib ExitStack collects managers as the program runs and closes them all when its own block ends:

Python
from contextlib import ExitStack
from pathlib import Path

names = ["a.txt", "b.txt"]
with ExitStack() as stack:
    handles = [stack.enter_context(open(n, "w", encoding="utf-8")) for n in names]
    for handle, text in zip(handles, ["one", "two"]):
        handle.write(text + "\n")
print("closed:", [h.closed for h in handles])
print(Path("a.txt").read_text(encoding="utf-8"), end="")
print(Path("b.txt").read_text(encoding="utf-8"), end="")

The exact output:

Output
closed: [True, True]
one
two

Each enter_context call enters one manager and registers its cleanup with the stack. Leaving the stack block runs every registered cleanup in reverse order of entry, the same rule as the comma form, and both files report closed afterward. The stack also works as the way to build a group of managers step by step, entering each one only after the step before it succeeded.

Which form for which job

Job Form Why
Use a resource that already ships as a manager with resource as name Setup and cleanup already live on the object, as with files
A manager with its own state or methods A class with enter and exit The pair of methods sits beside the state they manage
Clean up and let an error spread exit returning False Cleanup runs, then the caller sees the original error
Absorb one known error on purpose exit returning a true value The with statement treats the error as handled
A short setup and teardown pair @contextmanager on a generator function The yield splits setup from cleanup in one small function
A number of managers known only at run time ExitStack and enter_context Each manager registers as it is entered, all close together

Checklist

  • Before opening a file or session by hand, check whether it already works as a context manager and use with.
  • Before writing cleanup code after a block, remember it belongs in exit or after the yield, so it runs when the block fails too.
  • Before returning a true value from exit, name the single error the manager means to absorb; a blanket true hides faults.
  • Before listing many managers on one with line, check the exit order you need; managers leave in reverse order of entry.
  • Before fixing a count of managers in source, check whether the count comes from data; if it does, use ExitStack.
  • Before writing a @contextmanager function, put the yield inside try and finally so the cleanup survives an error in the block.

Sources

Keep Exploring