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

Steve Holden sholden at holdenweb.com
Tue Jun 4 12:01:56 EDT 2002


"John Roth" <johnroth at ameritech.net> wrote in message
news:ufpb3sn6332ub4 at news.supernews.com...
>
> "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.
>

> 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.
>

>>> a = b = [1,2,3]
>>> a += [4]
>>> a, id(a), b, id(b)
([1, 2, 3, 4], 269472088, [1, 2, 3, 4], 269472088)
>>>

Where did the rebinding take place? ISTM that "a" is still bound to the same
list, which has been modified in place.

> 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.)
>
That's because a type's implementation of augmented operations is allowed to
decide whether to rebind or update in place. Seems to me the exception is
caused because the tuple's hash would be changed, though I'm not familiar
with the implementation detail. That seemed reasonable to me.

> 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.
>
Clearly an explicit assignment to a tuple element is always going to fail,
so I don't really see what this would tell you.

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------







More information about the Python-list mailing list