Context managers and with
- Version
- 3.14
- Review
- Draft
Summary#
A with statement calls __enter__ before its block. Once __enter__ returns successfully, Python calls __exit__ on the way out, including when the block raises. contextlib.contextmanager builds a context manager from a generator that yields once.
Syntax#
with manager() as value:
pass
with (first() as a, second() as b):
pass
Example#
from contextlib import contextmanager
@contextmanager
def session(name):
print("open", name)
try:
yield name.upper()
finally:
print("close", name)
with session("db") as handle:
print("use", handle)
try:
with session("cache"):
raise RuntimeError("lookup failed")
except RuntimeError as error:
print("caught", error)
Expected output#
open db
use DB
close db
open cache
close cache
caught lookup failed
Common mistakes#
In a generator context manager, an exception from the block is raised at the yield. Without try and finally, the cleanup after yield is skipped. If you catch that exception inside the generator and do not raise it again, the with statement treats it as handled.
Version applicability#
The single-manager form and the example work on all Python 3 releases. The comma-separated multi-manager form was added in 3.1. CPython's default PEG parser accepts grouping these managers in parentheses from 3.9. Python 3.10 made that form officially supported.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0