tba tba - 19 days ago 5
Python Question

Python variable scope error

I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):

a, b, c = (1, 2, 3)

print(a, b, c)

def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()


However, when I uncomment line (B), I get an UnboundLocalError: 'c' not assigned at line (A). The values of a and b are printed correctly. This has me completely baffled for two reasons:


  1. Why is there a runtime error thrown at line (A) because of a later statement on line (B)?

  2. Why are variables a and b printed as expected, while c raises an error?



The only explanation I can come up with is that a local variable c is created by the assignment
c+=1
, which takes precedent over the "global" variable c even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.

Could someone please explain this behavior?

Answer

Python treats variables in functions differently depending on whether you assign values to them from within the function or not. If you assign any value to a variable, it is treated by default as a local variable. Therefore, when you uncomment the line, you are attempting to reference a local variable before any value has been assigned to it.

If you want the variable c to refer to the global c put

global c

as the first line of the function.

As of python 3, there is now

nonlocal c

that you can use to refer to the nearest enclosing (not necessarily global) scope.