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
TARGET
was included in thewith
statement, the return value from__enter__()
is assigned to it. - The
SUITE
is executed. - The context manager’s
__exit__()
method is invoked. - If an exception caused the
SUITE
to be exited, its type, value, and traceback are passed as arguments to__exit__()
. Otherwise, threeNone
arguments are supplied. - If the
SUITE
was 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 continueswith
the statement following thewith
statement.
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)