[Python-Dev] PEP 203 Augmented Assignment

M.-A. Lemburg mal@lemburg.com
Thu, 27 Jul 2000 15:01:51 +0200


Guido van Rossum wrote:
> 
> > > Simply put:
> > >
> > >     a += 1 IS NOT ATOMIC!
> > >
> > If that's the case, then why do we need augemented assignments
> > at all ?
> >
> > (I understood the atomicness being the main argument for
> > introducing augmented assigns.)
> 
> Huh?  Where did you get that idea?  Can you point to a message where
> this was indicated?

It was advertised this way by Thomas:

      http://www.python.org/pipermail/python-list/2000-June/060680.html

And since assignments in Python are thread safe, I thought it
would only be natural for augemented assigns to also be thread
safe which would have been a real advantage, since a=a+1 is not
thread safe.

All other uses simply boil down to reducing typing efforts, IMHO.
(But that shouldn't keep you from adding it to the language ;-)

Some comments:

> The reason for introducing it is that it's been the single-most
> requested feature ever since Python's inception.  I think the reason
> it's been requested so much is that it's a waste of typing skills as
> well as (and more importantly) unnecessary extra effort to deduce
> what's going on in code like
> 
>     a.b.f().x[i] = a.b.f().x[i] + 1

This can be written as:

result = a.b.f().x
result[i] = result[i] + 1
 
> Another important reason is that in cases like
> 
>     a[long_and_expensive_call()] = a[long_and_expensive_call()] + 1

Dito for this one:

i = long_and_expensive_call()
a[i] = a[i] + 1
 
> you want to avoid doing the long_and_expensive_call() twice.
> Introducing a temp variable reduces the readability of the code.

Not really... in fact if the name makes it clear what it refers
too, it can augment the readbility.

Besdies, a.b.f().x[i] isn't good style to begin with ;-)
 
> Note that my proposed semantics guarantee that in
> 
>     a[long_and_expensive_call()] += 1
> 
> the index is computed only once -- but this is not the same as
> atomicity (which has to do with other threads, signal handlers and
> similar asynchronous things).

Nevermind... 
I just wanted to hint at the added value of making these 
assignments atomic operations and not just an optimization
of a = a + 1.

-- 
Marc-Andre Lemburg
______________________________________________________________________
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/