Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "underlying code" of a Python `with` statement?

Tags:

python

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?

like image 615
Brondahl Avatar asked Oct 21 '25 11:10

Brondahl


1 Answers

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.

like image 72
Brondahl Avatar answered Oct 23 '25 00:10

Brondahl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!