Context Managers & the with Statement
🎓 Advanced · Topic 03
Context Managers & the with Statement
Guarantee resource cleanup — files, locks, database connections, timers — even when exceptions occur, using Python's context manager protocol.
⏱ ~45 min
🔴 Advanced
🛡️ Resource safety
The Context Manager Protocol
Any object implementing __enter__ and __exit__ can be used with with. __exit__ is always called — even if an exception is raised.
@contextmanager — Generator Shortcut
The contextlib.contextmanager decorator lets you write context managers as simple generator functions — code before yield is setup, after is teardown.
📌 Exactly one yield
A @contextmanager generator must yield exactly once. The yielded value is bound to the as variable. Yielding nothing is fine — just write yield.
Useful contextlib Utilities
suppress(*exc)Silently ignore specified exceptions
nullcontext()A no-op context manager, useful for optional contexts
ExitStack()Dynamically manage multiple context managers
redirect_stdout()Temporarily redirect output to a file or StringIO