1

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)
1
  • No because then you aren't using finally Commented Apr 12, 2022 at 8:04

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.