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

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Jun 4 04:01:04 CEST 2002


Gustavo Cordova <gcordova at hebmex.com> wrote:
>So, it's not actually a bug, but an artifact of the hoops
>Python needs to jump through in order to maintain total
>dynamism in data types.
>
>Instead of this:
>
>   a = ([1],[2],[3])
>   a[0] += [3]
>
>do this:
>
>   a = ([1],[2],[3])
>   t = a[0]
>   t += [3]
>
>there won't be any exception, because 't' *can* be rebinded
>to the value emmited by the += operation; *and* 'a' will
>also contain the same reference.
>
>It's not *totally* equivalent, because it's missing a
>single, last step:
>
>   a[0] = t
>
>*that* is what's raising the exception, which is what
>the += operator is trying to do in you're original version.
>

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.

I'd imagine that at some future time there would be a desire to split += to
two distinct operators, one for true in-place operator and one for the fake
one currently implemented for immutables.  That would remove the spurious
exceptions for mutable members of immutable structures.

A main hindrance to the change at that time would be the difficulty to
disambiguate the true intention of existing code with the += operator.
That's not unlike the difficulty involved with the division operator change.
Maybe it's better to change earlier?


Huaiyu



More information about the Python-list mailing list