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?
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?
PyCharm is right. If
open()
fails, an exception is raised, and neitherreturn
is reached.with
does not somehow protect you from an exception in the expression that produces the context manager. The expression afterwith
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 willwith
swallow an exception at this stage and silently skip the block.