Syntax
@contextmanager
def resource():
try: yield value
finally: cleanup()Examples
Custom Context Managers
Run as a Python 3.11+ script.
from contextlib import contextmanager
@contextmanager
def session():
print("open")
try:
yield {"ready": True}
finally:
print("close")
with session() as state:
print(state["ready"])- Expected output: open True close
- yield provides the value bound by as. The finally block runs when the with block exits, including exceptional exits.
Best practices
- Yield exactly once in a contextmanager generator.
- Place cleanup in finally and avoid swallowing exceptions unintentionally.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference