Scope rule pecularities

Carl Banks imbosol at aerojockey.invalid
Fri May 7 01:13:48 EDT 2004


Donn Cave wrote:
> 
> 
> In article <slrnc9kkdo.5fa.apardon at trout.vub.ac.be>,
> Antoon Pardon <apardon at forel.vub.ac.be> wrote:
> ...
>> Beside you missed the point. I don't need solutions, I know the
>> work arounds to make it work. The point is that although a += b
>> is supposed to be syntactic sugar for a.__iadd__(b), you need
>> a global (and even that won't help if you have nested functions
>> and the a is on an intermediate level) to make the first work
>> but not for the second.
> 
> += is a bit of a wart.  The only value in it is that you can
> execute this read-and-modify sequence with a single access in
> some cases where accesses matter because of side effects.
> (Single access higher up in an expression - e.g., if we have
> a[0][0] += 1, you skip an a[0].)  If that seems like a silly
> reason to take on this abominable kludge, I'm probably not
> explaining it well - wasn't my idea.


There is one other little benefit: it lets you avoid having to type
and maintain two identical expressions.

I kind of felt the same way you did until one day I had to write a
bunch of assignments looking like this:

  cell[4*(i+1)+j+1].wallratio[k] = cell[4*(i+1)+j+1].wallratio[k] - 0.1

(It was for a rogue-like game BTW.  Yes, if -= didn't exist, of course
I would set w = cell[4*(i+1)+j+1].wallratio and use w[k] = w[k] - 0.1
today.  Using -= is still an improvement over that.)

One other thing: for things like Numerical Python, where efficiency
matters, using += is usually faster than +.  That is, a[:] = c, a +=
b, is faster than a[:] = c+b.

A lot of nice little reasons to have it so I wouldn't call it a kludge
and certainly not abominable.


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list