When I try this code:
a, b, c = (1, 2, 3)
def test():
print(a)
print(b)
print(c)
c += 1
test()
I get an error from the print(c)
line that says:
UnboundLocalError: local variable 'c' referenced before assignment
in newer versions of Python, or
UnboundLocalError: 'c' not assigned
in some older versions.
If I comment out c += 1
, both print
s are successful.
I don't understand: why does printing a
and b
work, if c
does not? How did c += 1
cause print(c)
to fail, even when it comes later in the code?
It seems like the assignment c += 1
creates a local variable c
, which takes precedence over the global c
. But how can a variable "steal" scope before it exists? Why is c
apparently local here?
See also Using global variables in a function for questions that are simply about how to reassign a global variable from within a function, and Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope? for reassigning from an enclosing function (closure).
See Why isn't the 'global' keyword needed to access a global variable? for cases where OP expected an error but didn't get one, from simply accessing a global without the global
keyword.
See How can a name be "unbound" in Python? What code can cause an `UnboundLocalError`? for cases where OP expected the variable to be local, but has a logical error that prevents assignment in every case.