Is `with return .. return` unreachable code?

978 views Asked by At

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?

1

There are 1 answers

4
Martijn Pieters On BEST ANSWER

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.