[issue39037] Fix the trial order of the __exit__ and __enter__ methods in the with statement documentation

Géry report at bugs.python.org
Sun Dec 15 06:27:27 EST 2019


Géry <gery.ogam at gmail.com> added the comment:

@gvanrossum

By the way, is there any particular reason why the ``try`` statement implementation equivalent to the ``with`` statement given in PEP 343 puts the finally clause in an outer ``try`` statement instead of in the inner ``try`` statement? (cf. https://www.python.org/dev/peps/pep-0343/#specification-the-with-statement)

In other words, couldn't we simplify this:

```
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)
```

into that?

```
mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
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)
```

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39037>
_______________________________________


More information about the Python-bugs-list mailing list