Python context manager lifecycle diagram

@contextmanager lets you build a context manager from a generator in five lines. But its cleanup runs in a way that surprises people the moment an exception enters the with block — and that surprise usually means a leaked connection or an unclosed file.

The trap

A context manager built from a generator splits into two parts: code before yield is the setup (__enter__), code after yield is the teardown (__exit__).

from contextlib import contextmanager

@contextmanager
def open_resource(name):
    r = acquire(name)
    yield r        # __enter__ returns r
    r.close()      # __exit__: cleanup

This looks correct. It is — until something inside the block raises:

with open_resource("db") as r:
    do_work(r)     # raises ValueError
    # r.close() ???

Ask most people what happens to r.close() and they’ll say “it runs, that’s the whole point.” Not reliably.

What actually happens on an exception

When the with block throws, Python injects that exception into the generator at the yield. If your generator doesn’t catch it, the generator is closed and the code after yield is skipped. So r.close() never runs and your resource leaks.

# DANGEROUS: close() is skipped when do_work() raises
@contextmanager
def open_resource(name):
    r = acquire(name)
    yield r
    r.close()      # not reached on exception

The fix: try/finally

Wrap the yield so cleanup always executes, whether the block exits normally or via an exception:

@contextmanager
def open_resource(name):
    r = acquire(name)
    try:
        yield r
    finally:
        r.close()  # ALWAYS runs — normal exit and exceptions

This is the single most important rule of @contextmanager: post-yield code only runs on exceptions if it’s inside try/finally.

Gotcha: swallowing exceptions silently

Because the exception lands at your yield, it’s tempting to catch it. But if you catch and don’t re-raise, the caller never sees the error:

@contextmanager
def open_resource(name):
    r = acquire(name)
    try:
        yield r
    except Exception:
        pass          # BUG: the original error is silently swallowed
    finally:
        r.close()

Only catch what you intend to handle, and raise the rest through.

Gotcha: what as actually binds

with cm() as x: binds x to whatever you yield — not to the manager object. Yield None and x is None:

@contextmanager
def logged(label):
    print(f"enter {label}")
    yield            # yields None
    print(f"exit {label}")

with logged("job") as x:
    print(x)         # None

If you need the resource inside the block, yield it explicitly.

A real backend example: a transaction helper

Putting it together — a tiny DB transaction wrapper that commits on success and rolls back on any error:

import sqlite3
from contextlib import contextmanager

@contextmanager
def transaction(db_path):
    conn = sqlite3.connect(db_path)
    try:
        cur = conn.cursor()
        yield cur
        conn.commit()          # success -> commit
    except Exception:
        conn.rollback()        # error -> roll back
        raise                  # re-raise so the caller knows
    finally:
        conn.close()           # always released

with transaction("app.db") as cur:
    cur.execute("INSERT INTO logs VALUES (?)", ("hi",))
# commits here; on error it rolls back AND still closes the connection

Cheat sheet

  • Code before yield = setup (__enter__).
  • Code after yield = teardown — wrap it in try/finally or it’s skipped on exceptions.
  • yield value is what as binds.
  • Don’t swallow exceptions; raise after handling.
  • One yield only — a second raises RuntimeError.
  • Need richer logic (return values, explicit __exit__ checks)? Use a class with __enter__/__exit__ instead.