Home > Blockchain >  Python `with` statement semantic equivalent
Python `with` statement semantic equivalent

Time:04-12

I am confused why hit_except is necessary in the following code from the Python docs 8.5. The with statement:

The following code:

with EXPRESSION as TARGET:
    SUITE

is semantically equivalent to:

manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(manager, None, None, None)

Isn't that written more simply like this, or is there a difference I am missing?

manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)

try:
    TARGET = value
    SUITE
except:
    if not exit(manager, *sys.exc_info()):
        raise
else:
    exit(manager, None, None, None)

CodePudding user response:

finally guards any action that "exits" the current try scope.

If there's an action that skips the rest of the code, like return and exit(), or continue / break (in a loop), the else part will be skipped. In all these cases, the finally clause will still fire.

One example of forcibly skipping both finally and the __exit__ part of a context manager is os._exit(), which is possibly an overkill in most cases.

  • Related