Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python think this is a local variable?

Tags:

python

I have a global variable I called Y_VAL which is initialized to a value of 2.

I then have a function, called f() (for brevity), which uses Y_VAL.

def f():
    y = Y_VAL
    Y_VAL += 2

However, when trying to run my code, python gives the error message:

UnboundLocalError: local variable 'Y_VAL' referenced before assignment

If I remove the last line Y_VAL += 2 it works fine.

Why does python think that Y_VAL is a local variable?

like image 269
Paul Avatar asked Jul 13 '10 22:07

Paul


1 Answers

You're missing the line global Y_VAL inside the function.

When Y_VAL occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only assign to a global that way when you've explicitly declared global Y_VAL.

From the docs:

It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

like image 84
Mark Rushakoff Avatar answered Oct 21 '22 11:10

Mark Rushakoff