Nested scopes, and augmented assignment

Antoon Pardon apardon at forel.vub.ac.be
Wed Jul 5 10:29:51 EDT 2006


On 2006-07-05, Bruno Desthuilliers <onurb at xiludom.gro> wrote:
> Antoon Pardon wrote:
> (snip)
>> Well no matter what explanation you give to it, and I understand how it
>> works,
>
> I'm not sure of this.

Should I care about that?

>> 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.
>
> It's not about "finding a name/identifier", it's about the difference
> between (re)binding a name and mutating an object.

The two don't contradict each other. Python has chosen that it won't
rebind variables that are out of the local scope. So if the lefthand
side of an assignment is a simple name it will only search in the
local scope for that name. But if the lefthand side is more complicated
if will also search the outerscopes for the name.

Python could have chosen an approach with a "nested" keyword, to allow
rebinding a name in an intermediate scope. It is not that big a deal
that it hasn't, but I keep finding the result strange and somewhat
counterintuitive.

Let me explain why:

Suppose someone is rather new of python and writes the following
code, manipulating vectors:

  A = 10 * [0]
  def f(B):
    ...
    for i in xrange(10):
      A[i] += B[i]
    ...

Then he hears about the vector and matrix modules that are around.
So he rewrites his code naively as follows:

  A = NullVector(10):
  def f(B):
    ...
    A += B
    ...

And it won't work. IMO the principle of least surprise here would
be that it should work.

-- 
Antoon Pardon



More information about the Python-list mailing list