Assigning to variable from parent function: “Local variable referenced before assignment” [duplicate]

What you are seeing here is the difference between accessing and assigning variables. In Python 2.x you can only assign to variables in the innermost scope or the global scope (the latter is done by using the global statement). You can access variables in any enclosing scope, but you cannot access a variable in an enclosing scope and then assign to it in the innermost or global scope.

What this means is that if there is any assignment to a name inside of a function, that name must already be defined in the innermost scope before the name is accessed (unless the global statement was used). In your code the line c += 3 is essentially equivalent to the following:

tmp = c
c = tmp + 3

Because there is an assignment to c in the function, every other occurrence of c in that function will only look in the local scope for funcB. This is why you see the error, you are attempting to access c to get its current value for the +=, but in the local scope c has not been defined yet.

In Python 3 you could get around this issue by using the nonlocal statement, which allows you to assign to variables that are not in the current scope, but are also not in the global scope.

Your code would look something like this, with a similar line at the top of funcC:

   def funcB():
      nonlocal c
      c += 3
      ...

In Python 2.x this isn’t an option, and the only way you can change the value of a nonlocal variable is if it is mutable.

The simplest way to do this is to wrap your value in a list, and then modify and access the first element of that list in every place where you had previously just 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 the output:

funcA
c 0
funcB 3
funcC 5
funcB 8
funcC 5
end

Leave a Comment