[Python-ideas] Why does += trigger UnboundLocalError?

Georg Brandl g.brandl at gmx.net
Thu Jun 2 07:17:19 CEST 2011

On 01.06.2011 10:26, Carl M. Johnson wrote:
> On Tue, May 31, 2011 at 9:05 PM, Georg Brandl <g.brandl at gmx.net
> <mailto:g.brandl at gmx.net>> wrote:
>     Sure, this can only work if the local is assigned somewhere before the augmented
>     assign statement.  But this is just like accessing a local before its
>     assignment: in the case of
>     x = 1
>     def f():
>        print x
>        x = 2
>     we also don't treat the first "x" reference as a nonlocal.
> I don't think that's a counterexample to the point I'm trying to make. We all
> agree that if there's an x= somewhere in the function body, then we have to
> treat the variable as a local. The only possible way around that would be to
> solve the halting problem in order to figure out if a particular line of code
> will be reached or not. Agreed, sure, we have to treat the LHS of = as a local.
> But += is fundamentally different.

You keep saying that, but I just can't see how += is fundamentally different
from =, given its definition as x = x.__iadd__(y).

This is a situation that comes up from time to time, where it seems logical to
make a change that satisfies "DWIM" feelings, but makes the languge more
inconsistent by introducing special cases.  This doesn't feel right to me (and
the Zen agrees ;)


More information about the Python-ideas mailing list