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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With