Reputation: 955
With a flow like this:
def func():
try:
result = calculate()
finally:
try:
cleanup()
except Exception:
pass
return result
There is a warning about Local variable 'result' might be referenced before assignment:
But I can't really see how that's possible. One of these must be true:
calculate()
raises an exception --> the return statement will never get reached, so result is not referenced againcalculate()
does not raise an exception --> result is successfully assigned, and the return statement returns that valueHow would you ever get result
referenced before assignment? Is there an implementation of calculate
and cleanup
which could demonstrate that happening?
Upvotes: 4
Views: 2274
Reputation: 740
This is a false positive of PyCharms warning heuristics. As per the Python specification, the code behaves as you describe and result
can only be reached when set.
According to 8.4 in the Python documentation:
If the finally clause executes a return, break or continue statement, the saved exception is discarded:
>>> def f():
... try:
... 1/0
... finally:
... return 42
...
>>> f()
42
The Python interpreter will ignore the exception that was caused by calculate()
if the finally
block contains a return
, break
, or continue
statement.
This means that with the implementation you provided, where the finally
block has neither of the words specified above, the exception caused by calculate
won't be discarded, so the result
variable won't be referenced, meaning that this warning is useless.
Upvotes: 3