Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable 'result' might be referenced before assignment

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:

wat

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 again
  • calculate() does not raise an exception --> result is successfully assigned, and the return statement returns that value

How would you ever get result referenced before assignment? Is there an implementation of calculate and cleanup which could demonstrate that happening?

like image 618
noob overflow Avatar asked Oct 26 '25 11:10

noob overflow


1 Answers

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.

like image 113
LITzman Avatar answered Oct 29 '25 00:10

LITzman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!