UnboundLocalError on local variable when reassigned after first use

The following code works as expected in both Python 2.5 and 3.0:

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?

12 Answers
12

Leave a Comment