Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `with return .. return` unreachable code?

PyCharm warns about this code, saying the last return is unreachable:

def foo():
    with open(...):
        return 1
    return 0

I expect that the second return would execute if open() failed. Who's right?

like image 394
Filip Haglund Avatar asked Dec 19 '22 11:12

Filip Haglund


1 Answers

PyCharm is right. If open() fails, an exception is raised, and neither return is reached.

with does not somehow protect you from an exception in the expression that produces the context manager. The expression after with is expected to produce a context manager, at which point it's __exit__ method is stored and it's __enter__ method is called. The only outcomes here are that either the context manager is successfully produced and entered, or an exception is raised. At no point will with swallow an exception at this stage and silently skip the block.

like image 65
Martijn Pieters Avatar answered Dec 22 '22 16:12

Martijn Pieters