Relax Syntax for Augmented Arithmetic?

Steve Holden steve at holdenweb.com
Fri Jan 23 13:53:55 CET 2009


Aahz wrote:
> In article <87hc3un1vn.fsf.mdw at metalzone.distorted.org.uk>,
> Mark Wooding  <mdw at distorted.org.uk> wrote:
>>  * Python augmented-assignment (`+=', for example) is inconsistent.
>>    Depending on what type of object the left-hand side evaluates to, it
>>    may /either/ mutate that object, /or/ assign a new value to the
>>    expression.
> 
> Actually, that is not correct.  The augmented assignment always binds a
> new value to the name; the gotcha is that with a mutable object, the
> object returns ``self`` from the augmented assignment method rather than
> creating a new object and returning that.  IOW, the smarts are always
> with the object, not with the augmented assignment bytecode.
> 
> The best way to illustrate this:
> 
>>>> a = (1, ['foo'], 'xyzzy')
>>>> a[1].append('bar')
>>>> a
> (1, ['foo', 'bar'], 'xyzzy')
>>>> a[1] = 9
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: object doesn't support item assignment
>>>> a
> (1, ['foo', 'bar'], 'xyzzy')
>>>> a[1] += ['spam']
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: object doesn't support item assignment
>>>> a
> (1, ['foo', 'bar', 'spam'], 'xyzzy')

I understand what you are saying, but if the id() associated with a name
doesn't change after augmented assignment it seems a little wrong-headed
to argue that "the augmented assignment always binds a new value to the
name".

What you are actually saying is that it's up to the method that
implements the augmented assignment whether the same (mutated) object or
a different one is returned, right? And that the left-hand side of the
assignment is always bound to the result of that method.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list