with Statement
Syntax
with EXPRESSION as TARGET:
SUITE
as TARGET is optional.
Execution Steps
- The context expression (the expression given in the
EXPRESSION) is evaluated to obtain a context manager. - The context manager’s
__enter__()is loaded for later use. - The context manager’s
__exit__()is loaded for later use. - The context manager’s
__enter__()method is invoked. - If
TARGETwas included in thewithstatement, the return value from__enter__()is assigned to it. - The
SUITEis executed. - The context manager’s
__exit__()method is invoked. - If an exception caused the
SUITEto be exited, its type, value, and traceback are passed as arguments to__exit__(). Otherwise, threeNonearguments are supplied. - If the
SUITEwas exited due to an exception, and the return value from the__exit__()method wasFalse, the exception is reraised. If the return value was true, the exception is suppressed, and execution continueswiththe statement following thewithstatement.
semantically equivalent to:
manager = (EXPRESSION)
enter = type(manager).__enter__ # Not calling it yet
exit = type(manager).__exit__ # Not calling it yet
value = enter(manager)
hit_except = False
try:
TARGET = value # Only if "as VAR" is present
SUITE
except:
hit_except = True
if not exit(manager, *sys.exc_info()):
raise
finally:
if not hit_except:
exit(manager, None, None, None)