Skip to content

Commit 0fd6b3e

Browse files
committed
Add the try statement equivalent code of a with statement
1 parent 178721a commit 0fd6b3e

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

Doc/reference/compound_stmts.rst

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,13 +430,36 @@ The execution of the :keyword:`with` statement with one "item" proceeds as follo
430430
value from :meth:`__exit__` is ignored, and execution proceeds at the normal
431431
location for the kind of exit that was taken.
432432

433+
The following code::
434+
435+
with expression as target:
436+
suite
437+
438+
is semantically equivalent to::
439+
440+
manager = (expression)
441+
value = type(manager).__enter__(manager)
442+
exit = type(manager).__exit__
443+
target = value
444+
exception = False
445+
446+
try:
447+
suite
448+
except:
449+
exception = True
450+
if not exit(manager, *sys.exc_info()):
451+
raise
452+
finally:
453+
if not exception:
454+
exit(manager, None, None, None)
455+
433456
With more than one item, the context managers are processed as if multiple
434457
:keyword:`with` statements were nested::
435458

436459
with A() as a, B() as b:
437460
suite
438461

439-
is equivalent to ::
462+
is semantically equivalent to::
440463

441464
with A() as a:
442465
with B() as b:

0 commit comments

Comments
 (0)