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 neitherreturnis reached.withdoes not somehow protect you from an exception in the expression that produces the context manager. The expression afterwithis 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 willwithswallow an exception at this stage and silently skip the block.