πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Context Managers: Suppression, Stacks, and Async Wrappers

Python Patterns🟒 Free Lesson

Context Managers: Suppression, Stacks, and Async Wrappers

The with statement promises one thing: the block is entered exactly once and the cleanup runs exactly once, whether the block finishes, raises, or returns early. Most Python code only ever uses with open(...), which hides a surprisingly rich protocol β€” exception suppression semantics, generator-based shortcuts, a stack for a number of resources you cannot know in advance, and an async twin that awaits its own teardown. This lesson covers the contract itself, then the tools for when the simple form runs out.

What You'll Learn

  • 1State the exact arguments and return semantics of __exit__
  • 2Write a generator-based context manager without hitting the classic RuntimeError
  • 3Suppress or translate exceptions deliberately rather than by accident
  • 4Clean up a dynamic number of resources with ExitStack, in sync and async code

The contract Python actually honours

A context manager is any object with __enter__ and __exit__. Python calls __enter__ once on entry and uses its return value as the value of the with ... as target. It calls __exit__ once on the way out, always, passing three arguments when an exception occurred: the exception type, the exception instance, and the traceback. If the block completed normally, all three are None.

The detail that decides half of the bugs is the return value of __exit__. Returning a truthy value tells Python "this exception is handled, suppress it" β€” the with statement swallows the error and execution continues after the block. Returning False or None lets the exception propagate. Nothing in the signature says "suppressed", so a manager that accidentally returns a truthy value from a cleanup helper silently eats real failures, and the bug surfaces far from its cause.

python
class Transaction:
    def __init__(self, connection):
        self.connection = connection

    def __enter__(self):
        self.connection.execute("BEGIN")
        return self.connection

    def __exit__(self, exc_type, exc, tb):
        if exc_type is None:
            self.connection.execute("COMMIT")
        else:
            self.connection.execute("ROLLBACK")
        return False   # never swallow the exception


class SuppressAll:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        return True    # every exception is swallowed

Compare the two managers. The transaction inspects the exception only to decide how to clean up and then re-raises by returning False, which is the correct shape for resource managers. SuppressAll returns True unconditionally, which is correct only when swallowing is the entire purpose of the object β€” and dangerous when it is not.

Generator-based managers, and the trap in them

contextlib.contextmanager turns a generator with a single yield into a context manager: everything before the yield is __enter__, the yielded value is the as target, and everything after runs during __exit__. Code after the yield runs whether or not an exception occurred, so you can inspect sys.exc_info() or use try/finally to branch.

python
import time
from contextlib import contextmanager


@contextmanager
def timed(label):
    start = time.perf_counter()
    try:
        yield {"label": label}
    finally:
        elapsed = time.perf_counter() - start
        print(f"{label} took {elapsed:.4f}s")


with timed("indexing") as info:
    sum(range(200_000))
print(info["label"])   # indexing

The classic trap is yielding inside a try whose finally also yields, or yielding from a function that has more than one yield. A @contextmanager generator must suspend exactly once; a second suspension raises RuntimeError: generator didn't stop, and attempting to return a value from the generator raises RuntimeError: generator didn't stop after throw(). Keep the body to one yield, put cleanup in finally, and return nothing.

Suppressing exceptions on purpose

Blanket try/except blocks hide defects. When you genuinely expect a specific failure and can proceed without it, say so with contextlib.suppress, which narrows the handled types at the call site and leaves the body uncluttered.

python
import os
from contextlib import suppress, nullcontext


with suppress(FileNotFoundError):
    os.remove("scratch.tmp")   # already gone is fine


with suppress(KeyError):
    cache.pop("expired")


def session(persistent):
    if persistent:
        return open("state.json", "a")
    return nullcontext()       # no file, same with-block


with session(persistent=False) as handle:
    if handle:
        handle.write("{}")

nullcontext is the quiet hero: it lets a function return either a real resource or a no-op stand-in so callers keep one code path. Use it instead of returning None and sprinkling conditionals through the caller. The rule for both tools is the same β€” suppress only exceptions you can name and only where continuing is genuinely correct.

ExitStack: cleanup for resources you cannot count

Hard-coding a with chain works when the number of files, sockets, or locks is known when you write the code. It fails when the count comes from a list, a plugin registry, or user input. ExitStack collects context managers dynamically and unwinds them in reverse order, exactly like nested with blocks.

python
from contextlib import ExitStack


def tail_all(paths, limit=200):
    with ExitStack() as stack:
        readers = [stack.enter_context(open(path, encoding="utf-8")) for path in paths]
        out = []
        for reader in readers:
            lines = reader.readlines()
            out.extend(lines[-limit:])
        return out


print(tail_all(["a.txt", "b.txt"], limit=1)[:1])

Ordering is the reason ExitStack exists as more than a convenience: if one manager acquires a lock and the next opens a file guarded by it, unwinding must release the file first. The stack guarantees reverse order and, because every entered manager is registered before the next line runs, an exception partway through the loop still cleans up everything already acquired β€” the case where a hand-rolled list of resources leaks.

The async twin

Async cleanup needs its own protocol: __aenter__ and __aexit__, written by hand or produced by contextlib.asynccontextmanager. The rules are otherwise identical, including the suppression return value, and the same one-yield restriction applies.

python
import asyncio
from contextlib import asynccontextmanager, aclosing


@asynccontextmanager
async def connection_pool(size):
    pool = [{"id": i, "busy": False} for i in range(size)]
    print(f"pool up with {size} slots")
    try:
        yield pool
    finally:
        print("pool drained")


async def main():
    async with connection_pool(4) as pool:
        await asyncio.sleep(0)
        print(len(pool))


asyncio.run(main())

Async generators used as resources need contextlib.aclosing, because abandoning an async generator does not reliably flush its finally when the event loop is closing. The habit to build is symmetrical: if the acquisition awaits, the release must await too, and a library that only offers a synchronous close should be wrapped so it runs in an executor instead of blocking the loop.

The same protocol models locks, transactions, and time

Files are only the most common guest. threading.Lock, tempfile.TemporaryDirectory, decimal.localcontext, unittest.mock.patch, and multiprocessing.Pool are all context managers, and once you recognise the protocol you can write your own for anything that must be undone. A cache with a scoped flush, a rate limiter that pauses while a block runs, a test fixture that patches settings, or a span exporter that closes a trace β€” each is a handful of lines with __enter__ and __exit__, and each gains correct behaviour under exceptions for free.

The pattern shows up in frameworks too. Django's transaction.atomic rolls back precisely because __exit__ received an exception; SQLAlchemy sessions expire objects on exit; pytest fixtures with yield tear down after the test, whatever its outcome. In every case the value of the protocol is the same: cleanup lives next to acquisition, so a reader cannot use one without the other, and control flow that would have been scattered across try and finally collapses into a single indented block.

One caveat travels with the territory: a context manager instance that is entered twice β€” nested, or from two threads β€” shares state between the two entries. Keep managers stateless where you can, or store per-entry state in locals and return self only when the object genuinely can be re-entered.

Which tool for which situation

SituationToolWhy
One file, lock, or connectionwith open(...) or a classThe straightforward case
Reusable rule across many classes@contextmanagerTen lines instead of a class
Expected, harmless failuresuppressNames the exception at the call site
Resource may not existnullcontextKeeps one code path in the caller
Count of resources is dynamicExitStackReverse-order unwinding, exception safe
Cleanup awaits@asynccontextmanagerThe event loop needs __aexit__

Common Mistakes

Returning a truthy value from __exit__ in a resource manager

Fix: Return False unless swallowing the exception is the documented purpose of the manager

Writing more than one yield in a @contextmanager generator

Fix: Keep a single yield, put cleanup in finally, and never return a value from the generator body

Collecting opened resources in a plain list and closing them in a finally loop

Fix: Use ExitStack so unwinding stays in reverse order and partial acquisition still cleans up

Closing an async resource with a blocking synchronous call

Fix: Await the async close, or hand the blocking one to an executor so other tasks keep running

Best Practices

  • Write __exit__ so that it cleans up first and only then decides whether to suppress
  • Prefer contextlib.suppress with explicit exception types over a bare except block
  • Return nullcontext instead of None from functions that may or may not own a resource
  • Keep context managers small and single-purpose; a manager that also does business logic is a hidden control-flow fork
  • Test a context manager by raising inside the with block and asserting both the cleanup side effect and the propagation behaviour

Interview Questions

Q1: What do the three arguments to __exit__ mean, and when are they None?

They are the exception type, instance, and traceback. They are all None when the with block completed normally; otherwise they describe the exception that is unwinding the block. A truthy return value suppresses it.

Q2: Why does a @contextmanager generator raise RuntimeError if it yields twice?

The decorator expects exactly one suspension: it sends the value to the yield for __enter__, then throws any exception at that same point for cleanup. A second yield means the generator never reached the state the wrapper requires.

Q3: How do you clean up a list of files opened at runtime?

ExitStack. Enter each file with stack.enter_context in a comprehension, and the stack unwinds them in reverse order on exit, including when an exception occurs partway through acquisition.

Q4: What is the async equivalent of @contextmanager?

contextlib.asynccontextmanager, which defines __aenter__ and __aexit__ around a single await yield. Async generators held as resources additionally need contextlib.aclosing to guarantee finalisation.

Key Takeaways

  • __exit__ always runs, receives exception details when there is an exception, and suppresses only when it returns a truthy value
  • Generator-based managers must yield exactly once and should return nothing
  • suppress and nullcontext express expected absence and no-op cleanup more clearly than conditionals
  • ExitStack handles a dynamic number of resources with reverse-order unwinding and partial-acquisition safety
  • Async resources need the async protocol end to end; a blocking close defeats the event loop
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

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement