tahsmith tahsmith -4 years ago 82
Python Question

UnboundLocalError when using += on list. Why is `nonlocal` needed here when directly calling __iadd__ works fine?

Consider this code:

def main():
l = []

def func():
l += [1]


if __name__ == '__main__':

It will produce:

Traceback (most recent call last):
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 14, in <module>
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 11, in main
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 9, in func
l += [1]
UnboundLocalError: local variable 'l' referenced before assignment

This itself can be fixed by either using
nonlocal l
at the start of
or using
directly instead of

Question: Why is
needed here?

This is very surprising to me.

Answer Source

+= is the augmented assignment operator; it roughly translates to:

def func():
    l = l + [1]

If you were to replace l += [1] with a call to object.__iadd__(), you can't ignore the return value of that call if you were to use it properly:

def func():
    l = l.__iadd__([1])

Both of those translations also need a nonlocal statement, because both access l and assign back to l.

You can get away with ignoring the return value of object.__iadd__ because list objects are mutable; the list is mutated in-place. But then you may as well use the list.extend() call in that case:

def func():

list.__iadd__(), under the covers, calls list.extend() before returning self.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download