The following code works perfectly:
def f():
a = []
def g(x):
a.append(x)
print(a)
return g
a = f()
a(0)
a(1)
But when I replace a.append(x)
with a += [x]
I get an UnboundLocalError: local variable 'a' referenced before assignment
usually solved with a nonlocal a
declaration inside nested function.
Why this difference of behaviour on closures?