0

The code is like this:

import numpy as np

def f1():
    if False:
        del np
        import numpy as np
    return np.zeros(1)

if __name__=="__main__":
    a = f1()

When I run this code, I get the error message:

UnboundLocalError: local variable 'np' referenced before assignment

Why does 'np' become local?

The "if False" block should not affect my program at all, since it cannot be executed.

But when I delete the "if" block, the code works.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Because `import numpy as no` is an implicit assignment to the variable `np`, and any assignments inside a function make the variable local **at compile time** – juanpa.arrivillaga Jan 03 '20 at 03:15
  • In your case, the assignment happens because inside the `if` block, `np` was imported, thus `np` becomes a declared local assignment inside `f1`. As the assignment never happens, it will then trigger the exception as shown. – metatoaster Jan 03 '20 at 03:16
  • `import numpy as np` inside the function is an assignment to a local name `np` that hides the global `np`. The statement.on the prior line, `del np`, is treated by the Python compiler as referencing the local name which you can't do before it's created. It doesn't matter that it's surrounded by `if False:`β€”the Python compiler does not treat that as dead code. – Steven Rumbalski Jan 03 '20 at 03:23

0 Answers0