Back to Explore
GuideVibeFix editorialUpdated Nov 23, 2026

Python Context Managers from Scratch: with, __enter__/__exit__, contextlib, and async with

A context manager is the promise set up on entry, clean up on exit. This guide builds a Timer with __enter__/__exit__, explains why __exit__ returning True swallows exceptions, rewrites it with contextlib, and proves the point with a lock: 20000 increments with the lock, 5004 without. Standard library only, Python 3.12.3.

Real photo: hands typing Python code on a laptop, with a Python logo sculpture on the desk

Python developers use context managers every day, often without realizing it: with open("data.txt") as f: is one. Its working model is a single sentence: set up on entry, clean up on exit — and the cleanup runs no matter what happens in between, even if an exception is raised. Files must be closed, locks released, database transactions committed or rolled back, timers stopped: every resource that must be "put away after use" is a context manager's job. This guide explains the mechanism with Python 3.12.3, using only the standard library: first what the with statement does for you, then a hand-written class-based context manager, then the generator style from contextlib, and finally two real scenarios — thread locks and async code. The demo script is in the draft directory as demo243_zh.py, and the English rerun is rerun_en_demo243_g1.py; both produce the same numbers.

First, the problem it solves. A whole class of resources is awkward to handle: you must "acquire" them before use and "release" them after, and the release step is the easiest to skip when something goes wrong mid-way. File handles, database connections, thread locks, network sessions, temporary directories — all of them. Beginners write "open — use — close" in three steps, relying on "remembering to close"; experienced developers know that anything guaranteed by memory will eventually leak — a return in the middle of a function, a break in a loop, an exception halfway through, any of these can skip the close() line forever. Context managers take the "release" step out of the programmer's memory and write it into the syntax: once you enter a with block, the cleanup runs on exit, whether the block finishes normally, returns early, or raises. That guarantee is everything this guide is about. Once you understand it, every with in the standard library — opening files, taking locks, starting transactions, creating temporary directories — makes sense.

First, what with actually does for you

The most familiar form opens a file:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\n")

This line does more than it appears to: it opens the file on entering the with block and closes it on exit — even if write raises an exception halfway through, the file is still closed. Without with, the code looks like this:

f = open("notes.txt", "w", encoding="utf-8")
f.write("Line 1\n")
f.close()

It looks almost the same, but if write raises, f.close() never runs and the file handle leaks; even without an exception, an early return in the function skips close() too. Writing it correctly requires wrapping it in try/finally, which immediately doubles the code. That is the value of with: it writes the promise "cleanup will definitely run" into the syntax, so programmers no longer rely on memory. The demo hand-writes a NoteFile class that does the same thing: it writes three lines, prints "File closed" on exit, and the three lines read back are identical to what was written — the cleanup ran, and the content landed on disk. One more detail is worth noting: an exception raised inside a with block keeps propagating outward after cleanup runs. with does not "handle" exceptions; it only "cleans up the mess." Remember that division of labor — many people confuse "cleanup" with "handling exceptions," and the confusion starts here.

When to write one yourself

Not every "must be put away after use" scenario deserves a hand-written class. The test is simple: does this resource appear in many places, and is the cleanup logic the same every time? If it appears once, plain try/finally is more direct; if it appears three times or more, extract it into a context manager and the call site shrinks to a single with line. A timer is the classic example: measuring elapsed time is needed everywhere, and writing start = time.perf_counter() plus the subtraction at every site is verbose and easy to get wrong; extracted into a Timer, the call site is just with Timer("name"):, the elapsed time prints automatically, and you can read elapsed afterwards. Database transactions are the same: open a connection, begin a transaction, commit or roll back — every write operation walks that flow, and extracted into a context manager, the business code no longer sees commits and rollbacks at all, only the semantics "all of it happens, or none of it does." Conversely, if the cleanup logic differs every time — delete a file here, send a notification there — forcing it into one class only tangles the code, and honest try/finally is better. Remember the line: only repeated cleanup logic is worth encapsulating. A context manager saves repetition, not lines.

Before writing one by hand, check the standard library first — many ready-made context managers are already there, no need to reinvent the wheel. tempfile.TemporaryDirectory() creates a temporary directory and deletes the whole directory with its contents on exiting the with block, which is handy for tests and batch jobs; decimal.localcontext() temporarily changes decimal precision and restores it on exit; warnings.catch_warnings() temporarily suppresses a class of warnings and restores them outside the block. Even threading.Lock itself is a context manager — with lock: acquires and releases in one line. These built-ins cover most scenarios; only when the standard library has nothing and the cleanup logic repeats across your project is it worth writing your own. Check the standard library first, then decide whether to build the wheel — that is the least-effort order for using context managers.

Hand-written: __enter__ and __exit__

Any class that defines the two methods __enter__ and __exit__ can be used inside with — that is the context manager protocol. The demo writes a timer:

class Timer:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        self.start = time.perf_counter()
        print(f"Enter {self.name}: timing starts")
        return self
    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self.start
        print(f"Exit {self.name}: took {self.elapsed:.3f} s")
        return False  # do not swallow exceptions

Output:

Enter sleep 0.2 s: timing starts
Exit sleep 0.2 s: took 0.200 s
Timed result: 0.200 s (expected about 0.2 s)

Three details are worth pausing on. First, whatever __enter__ returns is what lands after as: here it returns self, so as t gets the timer itself and t.elapsed can be read after exit; when opening a file, __enter__ returns the file object, so as f gets the file. Second, __exit__ receives three arguments — the exception type, the exception object, and the traceback; when the block raises nothing, all three are None. Third, the return value of __exit__ decides the exception's fate: returning False (or None) means "not handled, let the exception keep propagating"; only returning True means "I swallowed this exception." The timer returns False because a timer only measures time — it should not decide the fate of the caller's exceptions.

What happens when __exit__ returns True

This is the easiest trap for beginners, and the most important section of this guide. The demo writes a LoudExit whose __exit__ returns False:

try:
    with LoudExit():
        raise ValueError("demo exception")
except ValueError as e:
    print(f"Exception propagated outside the with block: {e}")

Output:

Enter LoudExit
Exit LoudExit: saw exception ValueError, not swallowing it
Exception propagated outside the with block: demo exception

__exit__ is called before the exception propagates outward — it gets a chance to clean up (close files, release locks, roll back transactions), and then the exception continues on its way, and the except outside the with still catches it. If return False were changed to return True, the ValueError would be silently swallowed on exiting the with block, the outer except would never catch it, and the program would carry on as if nothing had happened — maddening to debug. The rule is one line: unless your context manager exists specifically to handle a particular class of exceptions, __exit__ always returns False. The one legitimate exception-handler is already written in the standard library — suppress, in the next section.

contextlib: the generator style is less work

Writing a whole class for a small job is verbose, so the standard library's contextlib offers a generator style: one function and one yield make a context manager:

@contextlib.contextmanager
def timer2(name):
    start = time.perf_counter()
    print(f"Enter {name}")
    try:
        yield
    finally:
        print(f"Exit {name}: took {time.perf_counter() - start:.3f} s")

The output is the same as the class-based timer: enter, sleep 0.1 s, exit after 0.100 s. The code before yield is __enter__, and the code after yield is __exit__; yield must sit inside try/finally, or the cleanup after it will not run when the block raises — the most common mistake in the generator style. The demo also uses contextlib.suppress:

with contextlib.suppress(ZeroDivisionError):
    1 / 0
print("ZeroDivisionError was suppressed silently, program continues")

suppress means "if the named exception shows up in these lines, pretend it never happened" — it is the standard library's only context manager that is openly allowed to swallow exceptions, and it is far clearer than writing return True yourself: anyone reading the code can see at a glance that ignoring ZeroDivisionError here is deliberate, not a bug. Two more tools are worth knowing: contextlib.closing wraps an object that only has a close() method and no __enter__/__exit__ into a with; and contextlib.ExitStack lets you decide at runtime how many context managers to enter — for example, opening a variable number of files from configuration, with stack.enter_context(open(...)) in a loop, closing them all in last-in-first-out order on exit.

ExitStack: when the count is only known at runtime

ExitStack solves a problem the with syntax itself cannot: the number of files to open is not known when the code is written. Suppose a configuration lists five log files to open at once — nesting with five deep works, but changing the configuration to three files means changing the code; with ExitStack, the count does not matter:

with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
    # use files here; all close last-in-first-out on exit

On exiting the with block, ExitStack exits the registered context managers one by one in last-in-first-out order — as if it had written the nested with statements for you. More usefully, it can change its mind mid-flight: calling stack.pop_all() hands management over, letting the resources stay alive after the with block ends — for example, a function that opens a file and wants to return the file object to its caller without being responsible for closing it can transfer the stack's management. In real projects, ExitStack shows up most in test fixtures and batch scripts: tests that start a varying number of mock services based on parameters, batch jobs that open a varying number of files based on input — all "count known only at runtime" scenarios. Remember its place: with handles "the number of resources is known when the code is written," ExitStack handles "the number is known only at runtime."

Entering several at once: nesting and side-by-side

One with statement can enter several context managers at once, separated by commas:

with open("a.txt", encoding="utf-8") as fa, open("b.txt", encoding="utf-8") as fb:
    # use both files; they close last-in-first-out on exit

The exit order is last-in-first-out: fb closes first, fa second — the same order as ExitStack. When managers are nested, there is another guarantee worth knowing: if the outer manager entered successfully and the inner one raises on entry, the outer manager's __exit__ still runs — resources do not leak just because "the inner one never got in." That guarantee comes from the protocol itself, not from the programmer. In practice, the side-by-side form fits "the count is fixed and known when the code is written"; use ExitStack when the count varies; plain nested with is fine for one or two, but beyond three levels of nesting, switch to side-by-side or extract a function — the indentation gets unreadable first. One piece of trivia: since Python 3.10, a with statement can break multiple managers across lines inside parentheses without changing semantics, which works in 3.12 as well.

In practice: thread locks are the best example

The most convincing scenario for context managers is a lock. Four threads each add 5000 to the same counter; the expected result is 20000. The demo runs two groups:

with lock:
    counter["n"] += 1

Output:

With lock: 4 threads x 5000 = 20000 (expected 20000)
Without lock: 4 threads x 5000 = 5002 (expected 20000, lost 14998)

Bar chart: with the lock the counter reads 20000; without it this run measured only 5002, losing 14998 increments

The unlocked group lost three quarters of its increments — two threads read the same value, each added one, and wrote back the same value, so one increment was wasted. The demo has a deliberate design choice: the unlocked branch splits "read — modify — write" into three steps with a time.sleep(0) in between, yielding execution to widen the race window; otherwise CPython's global interpreter lock makes this small loop show almost no losses — on this machine, without that step, four runs of 20000 all came out perfect. Repeated runs land around 5000 (5000–5004), losing about 15000, a stable magnitude. This example shows two things: first, the value of a lock is not in "the addition itself" but in making "read — modify — write" an uninterruptible whole; second, with lock: guarantees the lock is released — even if the block raises, __exit__ releases it, so other threads are never stuck outside the door forever. Database transactions are the same idea: the with block commits on normal exit and rolls back on exception, and connection pools, file locks, and temporary-directory cleanup all follow this pattern.

The async version: async with

Async code has context managers too, differing by a single async:

@contextlib.asynccontextmanager
async def async_timer(name):
    start = time.perf_counter()
    print(f"Enter {name}")
    try:
        yield
    finally:
        print(f"Exit {name}: took {time.perf_counter() - start:.3f} s")

async def main():
    async with async_timer("async sleep 0.1 s"):
        await asyncio.sleep(0.1)

asyncio.run(main())

Output: enter, exit after 0.100 s — identical to the sync version. The rules are the same: async with pairs with __aenter__/__aexit__, and yield sits inside try/finally. In real projects, the most common async context managers are network connections: async with aiohttp.ClientSession() as session opens a session and closes the connection pool on exit; a database connection async with pool.acquire() as conn borrows a connection and returns it on exit. The async traps are the same as the sync ones: __aexit__ returning True swallows exceptions too. One confusion is worth clearing up: async with and await are different things. await means "wait for an async operation to finish"; async with means "enter an async context, and do async cleanup on exit" — closing a connection pool is itself an operation that must be awaited, and a sync __exit__ cannot await, which is why __aexit__ exists. If you write with open(...) inside an async def function, that is fine — opening a local file needs no waiting, so the sync with is enough; async with is only needed when the cleanup itself must be awaited (closing connections, waiting for server confirmation). The test is the same as in the sync case: does the cleanup need await?

The five traps beginners fall into

Trap one: __exit__ returning True swallows exceptions — unless the point is to handle a specific exception class (use suppress), always return False. Trap two: in the generator style, yield outside try/finally means cleanup code does not run when the block raises — the context manager is written for nothing. Trap three: reusing a context manager produced by one @contextmanager call — generators are single-use, and entering with a second time raises immediately; call the function again to make a fresh one. Trap four: __enter__ returning the wrong thing — whatever follows as is exactly what __enter__ returned, so returning None gives you None; to use the resource inside the block, return the resource itself. Trap five: thinking with catches exceptions — it does not; with only guarantees cleanup runs, exceptions still propagate, and try outside is still needed where it is needed. One more easily missed trap: if __exit__ itself raises, it masks the original exception — the information about the block's original exception is lost; cleanup code should wrap itself in try/except or make sure the cleanup operation itself cannot fail, such as closing a file that is already closed.

Summary and checklist

In one sentence: a context manager is the promise "set up on entry, clean up on exit" — __enter__ prepares, __exit__ cleans up, cleanup still runs when an exception arrives, and the exception itself keeps propagating outward. The class style fits resources with state that are reused (timers, connection pools, lock wrappers); the @contextmanager generator style fits one-off simple scenarios; suppress is the only tool that should openly swallow exceptions; closing and ExitStack handle objects that "only have close, no protocol" and scenarios where "the count is known only at runtime." After this guide, check yourself against this list: can you state what __enter__ and __exit__ each do? Can you explain the difference between __exit__ returning True and False? Can you write a generator context manager with try/finally? Can you explain where the gap between 20000 and 5002 in the lock example comes from? Can you write the async with version? Can you decide whether a scenario needs with, ExitStack, or plain try/finally? If all of those are yes, context managers are truly in hand. The best next exercise is to find the resources in your own vibe project that are "opened but not guaranteed closed" — database connections, temporary files, thread locks — wrap each in with, run the tests, and check the cleanup really runs; then find one cleanup routine repeated three times or more, extract it into your own context manager, and enjoy a call site that is a single with line. The full demo code is in the draft directory as demo243_zh.py, and the English rerun is rerun_en_demo243_g1.py; both produce the same numbers (the lock count is around 5000, stable in magnitude; repeated runs land between 5000 and 5004).

Boundary with published guides: this guide covers the context manager protocol (with, __enter__/__exit__, contextlib, the async version), not file reading and writing itself (covered in the Python basics file I/O guide), not a full analysis of thread contention (covered in the concurrency models guide, which compares threads, processes, and asyncio), and not the logging and exception-handling systems (covered in the logging and exceptions guides). Each guide covers its own stretch, with no overlap.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles