Behavior of += (was Re: [Python-Dev] Customization docs)
johnroth at ameritech.net
Tue Jun 4 20:15:49 EDT 2002
"Huaiyu Zhu" <huaiyu at gauss.almadan.ibm.com> wrote in message
news:slrnafps1c.4ea.huaiyu at gauss.almadan.ibm.com...
> 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
> >> operator implements two semantically distinct operations, chosen
> >> to some properties of the operands. This is not unlike the
> >of the
> >> division operator with distinct behaviors on floats and ints.
> >This is not an issue with '+='. It's an issue with assignment,
> >of whether it is standalone or combined with some other operation.
> The point is that += does not have to contain any assignment at all.
> most cases for mutable objects, the result is the same object
> This was the motivation for introducing += into Python in the first
> The need for assignment only comes from immutable objects, but its
> implementational implication extends to mutable objects as well,
> this spurious exception. It is spurious because the last assignment
> 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
I think you're mistaken. To consider the example at the top of
the thread in more detail, you would argue that the only operation
is the append operation against the second list which is the second
operand of the tuple.
The assignment occurs because the pointer to the list has to
be changed to point to the (possibly) new location of the list
in memory. In other words, the second element of the tuple
has to be rebound.
There is no way of avoiding this, since objects are known
internally by their location in memory, and if you change the
object, you may (not necessarilly will) change that object's
location. Therefore, the pointer to the object must also be
changed in this instance. That is what causes the exception.
More information about the Python-list