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

Andre Engels andreengels at gmail.com
Wed Jun 1 12:51:49 CEST 2011


On Wed, Jun 1, 2011 at 12:43 PM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:

> My first reaction was: +1 on the proposed change.  It seemed logical.
>
> Then I had a reservation: it would widen the semantic difference between
>        x += 1
> and
>        x = x + 1
> which could trip someone innocently making a "trivial" code change from the
> former to the latter (x unintentionally becomes a local).
>
> So how about going further and say that x is only interpreted as local if
> there is at least one NON-augmented assignment in which x appears as a
> target on the LHS but x does NOT appear on the RHS?
> I.e.
>    x = x + 1
> (like "x += 1") does not (by itself) make x local.
>
> Or is this getting too hard to explain?

I think so; it also has the same disadvantage you mention of getting a
semantic change from seemingly neutral changes, but for other changes.
For example

x = 1 if x == 0 else x-1

would keep x global, but changing it to:

if x == 0:
    x = 1
else:
    x = x-1

would not do so.

-- 
André Engels, andreengels at gmail.com



More information about the Python-ideas mailing list