[Python-Dev] inplace operators and __setitem__

Phillip J. Eby pje at telecommunity.com
Wed Sep 28 17:52:28 CEST 2005


At 05:40 PM 9/28/2005 +0200, Pierre Barbier de Reuille wrote:
>Rather than closing this as invalid, it would be wiser to update the
>documentation before ! Nothing corresponds to the current behavior.

I got my information from here:

http://www.python.org/2.0/new-python.html#SECTION000700000000000000000


>I think that in this page :
>http://docs.python.org/ref/augassign.html
>
>The last paragraph whould be replace by :
>
>"""
>For targets which are attribute (or indexed) references, the initial
>value is retrieved with a getattr() (resp. __getitem__) and the result
>is assigned with a setattr() (resp. __setitem__). Notice that the two
>methods do not necessarily refer to the same variable. When getattr()
>refers to a class variable, setattr() still writes to an instance
>variable. For example:
>"""
>
>That way it will be clearly defined in the documentation.

Actually, the broken part is this sentence:

"""Also, when possible, the actual operation is performed in-place, meaning 
that rather than creating a new object and assigning that to the target, 
the old object is modified instead."""

It is subtly misleading, and would be better stated as:

"""Also, when possible, the actual operation is performed in-place, meaning 
that rather than creating a new object the old object is modified 
instead.  In either case, however, the assignment to the target is still 
performed."""


>Now, one can wonder if the augmented assignment is really an
>improvement. Lots of errors are made because they are counter-intuitive.

Huh?


>For example, in the standard library, I found very few uses of "+=" with
>a mutable object, and none would be broken if "a += b" is to be
>replaced by "a = a+b". At worst, there will be a performance issue that
>will easily be fixed by using "extend" method for lists and
>corresponding methods for other objects.

The intended use case (as I understand it) for augmented assignment is to 
allow you to hint that an operation should be done in place *if* it can 
be.  It means that you are not expecting a new object to be the result, but 
are prepared for the possibility it *might* be a new object.


>My opinion is, redefining the augmented assignment is a problem given
>the assignment semantic, and perhaps we should get rid of it.

How is it a problem?  If the assignment semantic weren't what it is, what 
would it be good for?  You could just write an in-place method and be done 
with it.  The whole point is that it allows client code not to care whether 
it's in-place or not, and to allow implementations to decide (even at 
runtime) whether to return a different object or not.



More information about the Python-Dev mailing list