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
with obj as val: → obj.__enter__() called → return value assigned to val
with block executes (normal or exception)
obj.__exit__(exc_type, exc_val, exc_tb) called — cleanup guaranteed
contextlib.contextmanager enables simple generator-based implementation