I'm having terrible trouble trying to understand python scoping rules.
With the following script:
a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
Gives the unexpected (to me) output of:
Before setA Value of a is 7 Inside setA, a is now 42 After setA Value of a is 7
Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?
Global variables are special. If you try to assign to a variable a = value
inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global
statement inside the function:
a = 7
def setA(value):
global a # declare a to be a global
a = value # this sets the global value of a
See also Naming and binding for a detailed explanation of Python's naming and binding rules.