🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Context Managers: ExitStack and Async Cleanup

Python Context ManagersđŸŸĸ Free Lesson

Context Managers: ExitStack and Async Cleanup

Every resource in a long-running program has a lifetime: a file handle, a database transaction, a lock, a temporary directory, an HTTP session. If the end of that lifetime depends on remembering to write a cleanup call in the right place, then every early return, every raised exception, and every cancelled task is a leak. Context managers exist so the lifetime is attached to a block of code rather than to the author's discipline.

The protocol is deliberately small. An object with __enter__ and __exit__ can be used with the with statement; __enter__ produces the value the block works with, and __exit__ runs whether the block completes normally or raises. A generator wrapped by contextlib.contextmanager expresses the same two halves as the code above and below a yield. When the number of resources is not known until runtime, ExitStack collects them and unwinds them in reverse order. Async code gets the same shape through __aenter__ and __aexit__.

What You'll Learn

  • 1State the guarantees the context protocol makes on normal and exceptional paths
  • 2Write both class-based and generator-based context managers with correct exception handling
  • 3Use ExitStack to manage a runtime-sized set of resources
  • 4Mirror the sync protocol with async context managers without blocking the loop

The protocol, and what exit actually receives

A with statement performs four steps. It evaluates the context expression, calls __enter__ on the result, binds that return value to the optional as target, runs the block, and then calls __exit__. If the block raised, the exception is passed into __exit__ as three arguments, and a truthy return value from __exit__ suppresses the exception. That suppression is powerful and dangerous: it is how a manager implements "this failure is part of normal operation", and it is also how a typo silently swallows an error.

python
import time


class Traced:
    def __init__(self, name):
        self.name = name
        self.elapsed = 0.0

    def __enter__(self):
        self._start = time.perf_counter()
        print(f"enter {self.name}")
        return self

    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self._start
        print(f"exit {self.name} after {self.elapsed:.4f}s, exc={exc_type}")
        return False


def run_batch():
    with Traced("batch") as span:
        time.sleep(0.01)
        return span.elapsed


print(run_batch())

Returning False explicitly documents the intent to propagate. A manager that catches nothing should say so. Only return True when you have deliberately handled the exception, and log something so the suppression is visible.

Generator-based managers with contextmanager

Class-based managers are verbose when the body is a straight line of setup and teardown. contextlib.contextmanager lets you write the same thing as a generator: code before the yield is the enter half, the yield value is what the block receives, and code after the yield is the exit half. An exception raised inside the block is re-raised at the yield point, so a try/finally around the yield gives you teardown that runs on every path.

python
from contextlib import contextmanager
import tempfile
import shutil
from pathlib import Path


@contextmanager
def working_directory(prefix="scratch-"):
    path = Path(tempfile.mkdtemp(prefix=prefix))
    try:
        yield path
    finally:
        shutil.rmtree(path, ignore_errors=True)


@contextmanager
def transaction(conn):
    try:
        yield conn
    except Exception:
        conn.rollback()
        raise
    else:
        conn.commit()


with working_directory() as work:
    (work / "input.txt").write_text("alpha\n", encoding="utf-8")
    print(sorted(p.name for p in work.iterdir()))

The finally form is the safe default because it always cleans up. The try/except/else form shown for transaction does more: it inspects whether the block succeeded and chooses between commit and rollback, then re-raises so the caller still sees the original failure. What it must never do is swallow the exception by accident, which happens when a bare except: catches everything and forgets to re-raise.

ExitStack for a number of resources you only learn at runtime

Writing nested with statements works when the count is fixed. It fails when the resources come from a list, a configuration, or a discovery step. ExitStack collects any number of context managers, enters them in order, and exits them in reverse, releasing everything even if the middle of the block fails.

python
from contextlib import ExitStack, suppress, redirect_stdout
import io


def render_reports(templates):
    buffer = io.StringIO()
    with ExitStack() as stack:
        opened = [
            stack.enter_context(open(name, encoding="utf-8"))
            for name in templates
        ]
        stack.callback(print, f"rendered {len(opened)} templates")
        stack.enter_context(redirect_stdout(buffer))
        for handle in opened:
            for line in handle:
                buffer.write(line.upper())
    return buffer.getvalue()


print(render_reports(["a.txt", "b.txt"]))

Beyond enter_context, the stack offers callback for plain functions that are not context managers, and push for a manager you already hold. That combination is what makes it the right tool for dependency injection in tests: acquire locks, connections, and patches in any order, and be certain all of them unwind.

Async context managers

Async code needs the same guarantee, and the protocol is mirrored rather than replaced. A class implements __aenter__ and __aexit__, and is awaited with async with. The contextlib.asynccontextmanager decorator plays the role of contextmanager for generator-style definitions. The rule that keeps async code healthy is that anything awaited inside the manager must itself be awaited; a synchronous blocking call inside __aenter__ stalls the entire event loop.

python
import asyncio
from contextlib import asynccontextmanager


class Pool:
    def __init__(self, size):
        self.size = size
        self._idle = asyncio.Queue()
        self._all = []

    async def __aenter__(self):
        for i in range(self.size):
            conn = {"id": i, "busy": False}
            self._all.append(conn)
            await self._idle.put(conn)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        self._all.clear()
        while not self._idle.empty():
            self._idle.get_nowait()
        return False

    async def acquire(self):
        conn = await self._idle.get()
        conn["busy"] = True
        return conn

    async def release(self, conn):
        conn["busy"] = False
        await self._idle.put(conn)


@asynccontextmanager
async def session(pool):
    conn = await pool.acquire()
    try:
        yield conn
    finally:
        await pool.release(conn)


async def main():
    async with Pool(3) as pool:
        async with session(pool) as conn:
            await asyncio.sleep(0.01)
            print("used", conn["id"])


asyncio.run(main())

The same discipline applies as in synchronous code: never suppress an exception you have not handled, and keep teardown symmetric with setup.

Nesting order, and what unwinds first

Managers compose, and the composition order is not neutral. Nested with statements unwind in reverse: the last one entered is the first to exit, which is why a lock held outside a file handle releases after the file is closed, and why swapping the order can leave a file written after the lock is gone. ExitStack preserves the same discipline automatically, entering in call order and exiting in reverse, so code that builds the stack dynamically still unwinds correctly.

Asynchrony makes the ordering more consequential, because an exit half that awaits can interleave with other tasks. A manager whose teardown releases a shared connection should complete that release before control returns to the loop, otherwise another task can observe the resource as busy when it is actually free. Keeping teardown short, awaited, and free of new dependencies on the same resource is the rule that keeps composed async managers predictable.

The same reasoning applies to exceptions. When two nested managers both see the same exception, the inner one has the first chance to handle it, and whatever it does determines what the outer one receives. A manager that swallows an error changes the behaviour of everything above it, which is why suppression remains a decision to document rather than a convenience to sprinkle around.

Testing the exceptional path, not only the happy one

A context manager's contract is mostly about failure, so a test suite that only exercises the successful path proves very little. The minimum set is three cases per manager: the block completes and teardown runs, the block raises and teardown still runs with the exception visible to the manager, and the manager's own setup fails so the block never begins. Each case asserts on a observable effect, such as a counter incremented in teardown or a rollback flag on a fake connection.

Generator-based managers deserve one extra test, because the generator form makes it easy to write teardown that runs only on the happy path. Removing the finally and asserting that the test now fails on the raising path is a quick way to prove the protection is real rather than assumed.

A context manager used in async code needs the same three cases written with an async test runner, plus a check that no synchronous blocking call appears in the enter or exit halves. A test that merely awaits the block will not notice a blocking call; a test that measures the event loop's responsiveness during teardown will.

Lifetime rules that hold up in production

Three rules prevent most production incidents. First, make setup and teardown symmetric in the same file, so a reviewer can see the pairing. Second, keep __exit__ idempotent, because a block may be unwound during interpreter shutdown as well as during normal flow. Third, decide explicitly whether the manager owns the resource or merely borrows it; a manager that closes a connection it does not own will surprise the caller that still holds a reference.

Where the standard library already provides a manager, use it. open, tempfile, decimal.localcontext, contextlib.suppress, contextlib.redirect_stdout, and multiprocessing primitives all implement the protocol correctly, and hand-rolling a replacement is a reliable source of leaks.

Common Mistakes

Returning a truthy value from __exit__ by default

Fix: Return False unless you deliberately handled the exception, and log when you suppress

Forgetting try/finally in a generator-based manager

Fix: Put teardown after a finally so it runs on the exceptional path as well as the normal one

Calling blocking I/O inside an async context manager

Fix: Await async-native operations or offload blocking work to a thread executor

Closing a resource the manager does not own

Fix: Document ownership explicitly and let the owner close it, or take ownership with a flag

Best Practices

  • Write class-based managers for reusable library code and generator-based ones for local, linear setup
  • Use ExitStack whenever the number of resources is determined at runtime
  • Keep __exit__ idempotent so interpreter shutdown cannot cause a second failure
  • Prefer contextlib.suppress only around exceptions you truly expect
  • Test the exceptional path, not only the happy one, for every manager you write

Interview Questions

Q1: What does returning True from __exit__ do?

It suppresses the exception that was raised in the block, so it never reaches the caller. Use it only when the manager has genuinely handled the failure, and log the suppression.

Q2: Why is ExitStack better than nested with statements in a loop?

The number of resources is not known when the code is written. ExitStack enters each one as it arrives and unwinds them all in reverse order, even when a later acquisition fails.

Q3: What is the async equivalent of contextlib.contextmanager?

contextlib.asynccontextmanager, applied to an async generator whose yield produces the block value and whose surrounding try and finally run the teardown with await.

Key Takeaways

  • The context protocol guarantees teardown on both normal and exceptional paths
  • Passing a truthy value from __exit__ suppresses the exception, so the default is False
  • Generator-based managers express linear setup and teardown with one yield
  • ExitStack handles runtime-sized collections of resources and unwinds them in reverse
  • Async context managers mirror the sync protocol, but every operation inside them must be awaited
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement