Suppose you have:
with with_target_expression() as with_variable:
with_block_contents(with_variable)
I understand the basic high-level intent here - that the target / with_variable will be "gotten rid of" sensibly after the with_block_contents completes.
But what is the full "raw" / "basic" Python being called/implied by this?
An answer is this:
with_target = with_target_expression()
with_variable = with_target.__enter__()
exception_raised = False
try:
with_block_contents(with_variable)
except Exception:
exception_raised = True
exception_details = sys.exc_info()
should_suppress = with_target.__exit__(*exception_details)
if(not should_suppress):
raise
finally:
if(not exception_raised):
with_target.__exit__(None, None, None)
But the canonical answer can be found in the documentation for the with statement (which will be updated into the future)
The above code is nearly equivalent (but differently laid out) to what's in that link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With