Why does this code (using +=
) lead to an UnboundLocalError
?
>>> l = [1, 2, 3]
>>> def foo():
l += [4]
>>> foo()
UnboundLocalError: local variable 'l' referenced before assignment
I know that it makes sense if there is an assignment. But the +=
operator behaves more like an append (i.e. using the same object), see here:
>>> x = [1, 2, 3]
>>> old_id = id(x)
>>> x += [4]
>>> new_id = id(x)
>>> assert old_id == new_id # same id after applying `+=` operator
So from a behavior-driven point of view, the foo
function can also be seen like this (which works perfectly fine):
>>> l = [1, 2, 3]
>>> def foo():
l.append(4)
print(l)
>>> foo()
[1, 2, 3, 4]
Is this an optimization under the hood or what is the reason for this?