Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Context Managers and the `with` statement:
In Simple Words:
Guarantees resource acquisition and deterministic cleanup (e.g. closing files or DB connections) via __enter__ and __exit__, even if an unhandled exception is raised.
python
from contextlib import contextmanager
# 1. Class-based:
class DBTransaction:
def __enter__(self):
print("BEGIN TRANSACTION")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type: print("ROLLBACK")
else: print("COMMIT")
return False # Propagate exception if any
# 2. Generator-based with @contextmanager:
@contextmanager
def open_resource():
print("Acquired")
try: yield "RESOURCE"
finally: print("Cleaned up")