What is so special about += operator? [duplicate]
I wrote a code similar to the following and it gives me the local variable 'a' referenced before assignment
error. When I changed that a += [2]
into a.append(2)
, it worked.
def f():
a = [1]
def f1():
a += [2] # => no error with a.append(2)
f1()
print(a)
Why? Why the parser can't recognize the outside a
with +=
?
Solution 1:
It's an assignment to a
. It's basically syntactic sugar for
a = a.__iadd__([2])
The assignment makes a
a local variable when the code is generated, but then the RHS of the assignment tries to access that variable before at runtime it is defined.
a.append(2)
, on the other hand, is not an assignment. a
is a free variable whose value is taken from the closest enclosing scope.
If you want to assign to a non-local variable, you need to declare the name as non-local first.
def f():
a = [1]
def f1():
nonlocal a
a += [2]
f1()
print(a)