Nested scopes, and augmented assignment
Antoon Pardon
apardon at forel.vub.ac.be
Wed Jul 5 09:01:11 EDT 2006
On 2006-07-04, Diez B. Roggisch <deets at nospam.web.de> wrote:
> Tim N. van der Leeuw wrote:
>
>> Hi,
>>
>> The following might be documented somewhere, but it hit me unexpectedly
>> and I couldn't exactly find this in the manual either.
>>
>> Problem is, that I cannot use augmented assignment operators in a
>> nested scope, on variables from the outer scope:
>
><snip/>
>
>> Is this an implementation artifact, bug, or should it really just
>> follow logically from the language definition?
>
> From the docs:
>
> """
> An augmented assignment expression like x += 1 can be rewritten as x = x + 1
> to achieve a similar, but not exactly equal effect. In the augmented
> version, x is only evaluated once. Also, when possible, the actual
> operation is performed in-place, meaning that rather than creating a new
> object and assigning that to the target, the old object is modified
> instead.
> """
>
> The first part is the important one. If you expand
>
> x += 1
>
> to
>
> x = x + 1
>
> it becomes clear under the python scoping rules that x is being treated as a
> local to the inner scope.
>
> There has been a discussion about this recently on python-dev[1] and this
> NG - google for it.
Well no matter what explanation you give to it, and I understand how it
works, I keep finding it strange that something like
k = [0]
def f(i):
k[0] += i
f(2)
works but the following doesn't
k = 0
def f(i):
k += i
f(2)
Personnaly I see no reason why finding a name/identifier on the
leftside of an assignment should depend on whether the name
is the target or prefix for the target.
But maybe that is just me.
--
Antoon Pardon
More information about the Python-list
mailing list