I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:
The variables, REDGOLD
You need to declare the variable as global in each scope where they are being modified
Better yet find a way to not use globals. Does it make sense for those to be class attributes for example?
Found that variables in main
act like global "read only" variables in function. If we try to reassign the value, it will generate error.
Try:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
f()
It's ok.
But:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
A = [1,1,1,1,1]
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'A'** referenced before assignment
and:
#!/usr/bin/env python
RED=1
A=[1,2,3,4,5,6]
def f():
print A[RED]
RED = 2
f()
Generate
File "./test.py", line 6, in f
print A[RED]
UnboundLocalError: local variable **'RED'** referenced before assignment
global
make the global variable visible in the current code block. You only put the global
statement in main
, not in attack
.
ADDENDUM
Here is an illustration of the need to use global more than once. Try this:
RED=1
def main():
global RED
RED += 1
print RED
f()
def f():
#global RED
RED += 1
print RED
main()
You will get the error UnboundLocalError: local variable 'RED' referenced before assignment
.
Now uncomment the global statement in f and it will work.
The global
declaration is active in a LEXICAL, not a DYNAMIC scope.