Context Managers with Statement
suggest changeIntroduction
While Python’s context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, ensure that a resource is released when the with block ends, including when the block raises an exception. This topic explains and demonstrates the use of Python’s context managers.
Syntax
with expression as target:with expression as target, expression as target:
as target is optional. Since Python 3.10, parentheses may enclose the managers so the list can continue onto the next line.
Remarks
Context managers are defined in PEP 343. They are intended to be used as a more succinct mechanism for resource management than try ... finally constructs. The formal definition is as follows.
In this PEP, context managers provide __enter__() and __exit__() methods that are invoked on entry to and exit from the body of the with statement.
It then goes on to define the with statement as follows.
with EXPR as VAR:
BLOCK
The translation of the above statement is:
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)