Under The Hood
backend python CPython 3.12+

Context Managers: __enter__ / __exit__, @contextmanager, and ExitStack

Last updated
Prerequisites:
Python `with` statement basics
Exception handling (`try/finally`)
  • python
  • context-manager
  • exit-stack
  • contextlib
  • resource-management
  • with

Read at your depth

The practical view

Context managers guarantee resource cleanup via `with`. Create them by implementing `__enter__()` (returns resource) and `__exit__(exc_type, exc_val, exc_tb)` (handles cleanup). Alternatively, use the `@contextmanager` generator decorator from `contextlib`: everything before `yield` is setup, and everything in `finally` is teardown. `contextlib.ExitStack` manages dynamic or variable numbers of context managers programmatically.

The same idea in other frameworks

python equivalent
`with open('file') as f:` / `contextlib.ExitStack()`.

Legacy vs modern

Fragile Nested Try/Finally vs Dynamic ExitStack

Opening multiple dynamic files with nested try/finally causes deep nesting and leaked handles on failure; `ExitStack` cleans up in LIFO order.

before → after
Nested Try/Finally (Leaked Handles)
f1 = open('a'); try: f2 = open('b'); try: ... // ❌ Pyramid of doom
contextlib.ExitStack Dynamic Resource Pool
with ExitStack() as stack: files = [stack.enter_context(open(f)) for f in filenames] // ✅ NEW

Interview gotchas

Context

Interviewers test your knowledge of exception handling contracts in the Context Manager protocol.

The mechanical answer

To suppress an exception, the `__exit__` method **must explicitly return `True`** (or a truthy value): `def __exit__(self, exc_type, exc_val, exc_tb): return True`. If it returns `None`, `False`, or anything falsy, Python will re-raise the exception after `__exit__` finishes.

Trap

Never return `True` unintentionally in `__exit__` (e.g. from an accidental trailing expression), as it will silently swallow all crashes and bugs in the `with` block.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.