🚪

Context Managers — What the with Statement Actually Does

A protocol guaranteeing resource cleanup via __enter__ and __exit__

with open('data.txt') as f:
    content = f.read()
# f is already closed here — even if an error occurred

Resource cleanup guaranteed without try/finally. That's the core of context managers.

Internal Mechanism

__enter__ acquires the resource, __exit__ cleans up. __exit__ receives exception info as arguments. Return True to swallow exceptions, False to re-raise.

contextlib.contextmanager

Generator-based approach: yield before = __enter__, yield after = __exit__. Leverages generator's "pause execution" characteristic.

DB Transactions, Lock Management

DB connections, files, sockets, thread locks — context managers prevent leaks for any resource requiring cleanup.

Key Points

1

with obj as val: → obj.__enter__() called → return value assigned to val

2

with block executes (normal or exception)

3

obj.__exit__(exc_type, exc_val, exc_tb) called — cleanup guaranteed

4

contextlib.contextmanager enables simple generator-based implementation

Use Cases

File/DB connections — guarantee open and close timer() — auto-measure block execution time