1

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?

colidyre
  • 4,170
  • 12
  • 37
  • 53
  • 2
    I assume that if Python sees `a += b` in a function, it treats that as an assignment to `a`, not caring if that specific data type actually has different behavior for `iadd`. – John Gordon Jul 21 '22 at 19:04
  • FWIW: The answer of my question is not that present in the duplicate, so I link it here: https://stackoverflow.com/a/24261311/2648551 - The answer lies in the compiler using `LOAD_FAST` for `+=`. This can be seen by using `import dis; dis.dis(foo)`. So imo it falls a bit into a reasonable optimization topic, here. – colidyre Jul 21 '22 at 23:09

0 Answers0