download

Why did this with block leak a lock and hide an error?

Python~10 minReviewed 3 Dec 2026Free · No sign-in

Question

This code nests two custom context managers: Audit (a class) and open_lock (a @contextlib.contextmanager generator). When the with body raises RuntimeError, "release" never prints and "after with" still runs as if nothing failed.

  1. Predict the four lines the starter prints and explain why both bugs happen.
  2. Fix open_lock so cleanup always runs on exceptions.
  3. Fix Audit.__exit__ so exceptions propagate normally.
"CODE · PYTHON"
from contextlib import contextmanager


@contextmanager
def open_lock():
    print("acquire")
    yield
    print("release")


class Audit:
    def __enter__(self):
        print("enter")

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


with Audit(), open_lock():
    raise RuntimeError("boom")
print("after with")
Show hints (3)
  1. "WHERE ERRORS LAND"

    When the with body raises, @contextmanager throws that exception into the generator at yield. Code after yield does not run without a finally block.

  2. "EXIT RETURN VALUE"

    Python checks the truthiness of __exit__'s return value. What happens when __exit__ returns True instead of False or None?

  3. "FIX BOTH MANAGERS"

    Wrap yield in try ... finally inside open_lock, and return False (or omit return) from Audit.__exit__.

Show checked explanation

The starter prints enter, acquire, exit: RuntimeError, and after with. @contextmanager throws the body's exception into yield, so lines after yield skip unless wrapped in try ... finally. Then Audit.__exit__ returns True, which tells Python to suppress the exception. Wrap yield in try ... finally and return False from __exit__.

"SOLUTION · PYTHON"
from contextlib import contextmanager


@contextmanager
def open_lock():
    print("acquire")
    try:
        yield
    finally:
        print("release")


try:
    with open_lock():
        raise RuntimeError("boom")
except RuntimeError as err:
    print("caught:", err)
"OUTPUT"
acquire
release
caught: boom

Code run on CPython 3.12.10 against the buggy starter, both fixed context managers, and edge cases above. Checked by an editor other than the author.

Walkthrough

Inside with Audit(), open_lock():, managers enter left to right and exit in reverse order. When raise RuntimeError("boom") runs, each manager handles the error differently:

StepBuggy starterFixed managers
Enter Auditprints enterprints enter
Enter open_lockprints acquireprints acquire
Exit open_lockthrows at yield; skips releasefinally prints release; error re-raises
Exit Auditprints exit: RuntimeError; return True swallows itprints exit: RuntimeError; return False propagates
After withprints after with (crash hidden)RuntimeError reaches caller

Why open_lock leaked. @contextmanager runs the generator up to yield on __enter__. When the with body raises an error, __exit__ throws that exception into the paused generator right at yield. Without try ... finally, execution jumps straight out of open_lock and skips print("release").

Why Audit hid the error. The with protocol inspects the return value of __exit__(self, exc_type, exc, tb). Any truthy return value (True, 1, a non-empty string) tells Python the exception was handled and suppresses it. Returning False or None lets the exception continue upward.

Fix Audit by returning False (or removing return True). Running both fixed managers together prints enter, acquire, release, exit: RuntimeError, and caught: boom:

"PYTHON"
class Audit:
    def __enter__(self):
        print("enter")

    def __exit__(self, exc_type, exc, tb):
        print("exit:", exc_type.__name__ if exc_type else "ok")
        return False


try:
    with Audit(), open_lock():
        raise RuntimeError("boom")
except RuntimeError as err:
    print("caught:", err)

Unlike a bare try ... finally block in caller code, a context manager packages setup and cleanup once, so every caller gets safe teardown automatically.

Common mistakes

  • Leaving cleanup code right after yield in a @contextmanager function. Cleanup runs on normal exits, so simple tests pass while real exceptions leak the resource.
  • Returning a truthy status object such as return self.log or return "ok" from __exit__. Python treats any truthy value as permission to silence the exception.
  • Catching Exception inside @contextmanager without re-raising. Swallowing the error inside the generator hides crashes just like returning True from __exit__.
  • Assuming __exit__ runs if __enter__ fails. When __enter__ raises an exception, Python never calls that manager's __exit__.

Follow-up questions

  • "In with Audit(), open_lock():, what happens if open_lock() raises before yield?" Audit.__enter__ already succeeded, so Python still calls Audit.__exit__ with that exception. open_lock's own teardown does not run because it never reached yield. Any setup that can fail before yield must clean itself up before raising.
  • "When is suppressing an exception inside __exit__ actually wanted?" Only for narrow, explicit cases like contextlib.suppress(FileNotFoundError) or test assertions like pytest.raises(ValueError). Always check exc_type before returning True. Never return True unconditionally, because that also silences TypeError, MemoryError, and KeyboardInterrupt.
  • "What happens if __exit__ itself raises a new exception while handling an error?" The new exception replaces the original one as the active crash, with the original attached as __context__ in the traceback. Guard cleanup calls inside __exit__ carefully so a secondary logging or close error does not mask the real failure.

What a strong answer covers

Traces the LIFO exit order and explains both rules: @contextmanager throws exceptions into yield so cleanup needs try ... finally, and any truthy return from __exit__ suppresses the active exception. Also knows __exit__ is skipped if __enter__ fails.

Open in interactive practice deck →

Original OfferVibe question. Python The with Statement · Python Context Manager Data Model · Python contextlib.contextmanager.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.