What you see here is the difference between access and variable assignment. In Python 2.x, you can only assign variables in the inner scope or global scope (the latter is done using the global operator). You can access variables in any enclosing scope, but you cannot access a variable in the enclosing scope and then assign it to the innermost or global scope.
This means that if there is any naming within the function, that name should already be defined in the innermost area before the name is accessed (unless the global operator has been used). In your code, line c += 3 is essentially equivalent to the following:
tmp = c c = tmp + 3
Since the function has a destination c , any other occurrence of c in this function will be displayed only in the local area for funcB . That's why you see the error, you are trying to access c to get its current value for += , but in the local area c is not defined yet.
In Python 3, you can work around this problem by using a non-local operator that allows you to assign variables that are not in the current scope, but also not globally.
Your code will look something like this, with a similar line at the top of funcC :
def funcB(): nonlocal c c += 3 ...
This is not an option in Python 2.x, and the only way to change the value of a non-local variable is to change it.
The easiest way to do this is to wrap your value in a list, and then change and access the first element of this list anywhere you previously used the variable name:
def funcA(): print "funcA" c = [0] def funcB(): c[0] += 3 print "funcB", c[0] def funcC(): c[0] = 5 print "funcC", c[0] print "c", c[0] funcB() funcC() funcB() funcC() print "end" funcA()
... and conclusion:
funcA c 0 funcB 3 funcC 5 funcB 8 funcC 5 end
Andrew Clark Jan 19 '12 at 23:28 2012-01-19 23:28
source share