Is it just Syntactic Sugar ?

Thomas Wouters thomas at xs4all.net
Tue May 23 09:02:04 CEST 2000


On Tue, May 23, 2000 at 01:26:40AM +0000, Eric Hagemann wrote:

> a[x][f][g] = a[x][f][g] + 1

> does the python engine recompute the 'address' of the variable 'a[x][f][g]'
> twice ?

Yes, it does.

> Would the a+=1 for speed things up or is it just expanded to a=a+1 anyway ?

Yes, it would speed things up (for more complicated versions of 'a', in any
case) if implemented correctly. It couldn't just expand to a=a+1, because
'a' can have side effects, and you only want to trigger those once, in the
a+=1 case.

> I have found that

> p=a[x][f][g]
> p=p+1

> is faster than above so I kinda believe the 'address' is computed twice (I
> am leaping here)

Well, your code does something entirely different, that's why it executes
faster. It creates a new entry in the local namespace, called 'p', which
points to the same object as 'a[x][f][g]' points to. But then you modifiy
'p', not the object 'p' points to, so you lose the connection with
'a[x][f][g]'. You aren't modifying that list of lists (or dicts, or whatever)
at all.

Michael Hudson wrote a patch that adds augmented assignment to Python... It
used to have this webpage:
http://starship.python.net/crew/mwh/aug-patch.html

But that page is non-existant now. I'm not sure what happened to it, but the
URL to the patch directly still works:
http://starship.python.net/crew/mwh/aug-patch2.diff

However, the main reason for this patch is *not* speed... Speed is a minor
issue, in Python design. The main rason for augmented assignment is to
provide a convienent and obvious way for mutable objects to be modified:

MyLargeOBject = MyLargeObject + 1

Creates a new instance of MyLargeObject, copying all data, and then adds one
to it. Unless you override __add__ in MyLargeObject to avoid that, but then
you can never do:

MyOtherObject = MyLargeObject + 1

without modifying MyLargeObject as well. The += syntax is very good for
this, as you can be totally sure the programmer wants you to modify the
object, not create a new, modified copy.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list