'Python `with` statement semantic equivalent
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: SUITEis 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)
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | iBug |
