Behavior of += (was Re: [Python-Dev] Customization docs)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Jun 4 12:51:57 EDT 2002


John Roth <johnroth at ameritech.net> wrote:
>
>"Huaiyu Zhu" <huaiyu at gauss.almadan.ibm.com> wrote in message
>news:slrnafo7qv.37c.huaiyu at gauss.almadan.ibm.com...
>> Gustavo Cordova <gcordova at hebmex.com> wrote:
>
>>
>> Great explanation!  The problem stems from the fact that the current
>+=
>> operator implements two semantically distinct operations, chosen
>according
>> to some properties of the operands.  This is not unlike the situation
>of the
>> division operator with distinct behaviors on floats and ints.
>
>This is not an issue with '+='. It's an issue with assignment,
>regardless
>of whether it is standalone or combined with some other operation.

The point is that += does not have to contain any assignment at all.  In
most cases for mutable objects, the result is the same object (mutated).
This was the motivation for introducing += into Python in the first place.
The need for assignment only comes from immutable objects, but its
implementational implication extends to mutable objects as well, producing
this spurious exception.  It is spurious because the last assignment step is
not necessary.

>
>And I disagree that assignment implements two distinct operations.
>Assignment always rebinds. Always. In the examples cited, it
>attempted to rebind into a tuple, because that's what was asked
>for when the left hand side had a subscript.

This missed the point.  In-place operations should not contain assigments.

>
>The reason that the examples given at the top of the thread fail
>in such strange ways is simply that '+=' does not check whether
>the assignment is possible before doing the addition (or concatination,
>in the specific cases cited.)
>
>To see this, you could try the first example, using explicit '+' and
>'='. I suspect it would fail in exactly the same way, with exactly
>the same side effect.

Huaiyu



More information about the Python-list mailing list