Why did this with block leak a lock and hide an error?
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.
- Predict the four lines the starter prints and explain why both bugs happen.
- Fix
open_lockso cleanup always runs on exceptions. - Fix
Audit.__exit__so exceptions propagate normally.
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)
- "WHERE ERRORS LAND"
When the
withbody raises,@contextmanagerthrows that exception into the generator atyield. Code afteryielddoes not run without afinallyblock. - "EXIT RETURN VALUE"
Python checks the truthiness of
__exit__'s return value. What happens when__exit__returnsTrueinstead ofFalseorNone? - "FIX BOTH MANAGERS"
Wrap
yieldintry ... finallyinsideopen_lock, and returnFalse(or omitreturn) fromAudit.__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__.
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)
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:
| Step | Buggy starter | Fixed managers |
|---|---|---|
Enter Audit | prints enter | prints enter |
Enter open_lock | prints acquire | prints acquire |
Exit open_lock | throws at yield; skips release | finally prints release; error re-raises |
Exit Audit | prints exit: RuntimeError; return True swallows it | prints exit: RuntimeError; return False propagates |
After with | prints 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:
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
yieldin a@contextmanagerfunction. Cleanup runs on normal exits, so simple tests pass while real exceptions leak the resource. - Returning a truthy status object such as
return self.logorreturn "ok"from__exit__. Python treats any truthy value as permission to silence the exception. - Catching
Exceptioninside@contextmanagerwithout re-raising. Swallowing the error inside the generator hides crashes just like returningTruefrom__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 ifopen_lock()raises beforeyield?"Audit.__enter__already succeeded, so Python still callsAudit.__exit__with that exception.open_lock's own teardown does not run because it never reachedyield. Any setup that can fail beforeyieldmust clean itself up before raising. - "When is suppressing an exception inside
__exit__actually wanted?" Only for narrow, explicit cases likecontextlib.suppress(FileNotFoundError)or test assertions likepytest.raises(ValueError). Always checkexc_typebefore returningTrue. Never returnTrueunconditionally, because that also silencesTypeError,MemoryError, andKeyboardInterrupt. - "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 →