[Python-ideas] Why does += trigger UnboundLocalError?
Georg Brandl
g.brandl at gmx.net
Wed Jun 1 07:48:19 CEST 2011
On 01.06.2011 06:52, Carl M. Johnson wrote:
> We all know that the following code won't work because of UnboundLocalError and
> that to get around it, one needs to use nonlocal:
>
>>>> def accum():
> ... x = 0
> ... def inner():
> ... x += 1
> ... return x
> ... return inner
> ...
>>>> inc = accum()
>>>> inc()
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 4, in inner
> UnboundLocalError: local variable 'x' referenced before assignment
>
> But why does this happen? Let's think about this a little more closely: += is
> not the same as =. A += can only happen if the left-hand term was already
> defined. So, why does the compiler treat this as though there were an assignment
> inside the function?
Because x += y is equivalent to
x = x.__iadd__(y)
and therefore an assignment is going on here. Therefore, it's only logical to
treat it as such when determining scopes.
Georg
More information about the Python-ideas
mailing list