Can't get global variable inside method
I have a problem: when I try to use a global variable inside a method, an error occurs ("local variable" b "referenced before assignment"). Why is this not the case when the variable is a list item? I am new to python so please be careful :)
this works great:
a = [1]
def a_add():
a[0] += 1
a_add()
print(a)
but it doesn't:
b = 1
def b_add():
b += 1
b_add()
print(b)
source to share
When you try to assign something b
, Python executes LOAD_FAST
locally. You need to add global b
before trying to use b
.
def b_add():
global b
b += 1
From another point of view:
def b_add():
print(b)
Python instead executes LOAD_GLOBAL
which is loaded relative to globals. That way, when you did a[0]
, first it LOAD_GLOBAL
for a
and then store the value.
source to share
The official FAQ page has a detailed explanation of this error:
>>> x = 10
>>> def foo():
... print(x)
... x += 1
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
This is because when you make an assignment to a variable in scope, that variable becomes local to that scope and the shadow of any similar named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Hence when an earlier print (x) tries to print an uninitialized local variable and an error occurs.
And for the code:
a = [1]
def a_add():
a[0] += 1
a_add()
print(a)
It just reads the value and assigns the value to the first slot of the array global
, so no problem.
source to share