inconsistency with += between different types ?

Jonathan Hogg jonathan at onegoodidea.com
Mon Aug 5 17:40:54 EDT 2002


On 5/8/2002 20:50, in article aimku1$22ce$1 at nntp6.u.washington.edu, "Donn
Cave" <donn at u.washington.edu> wrote:

> The way I see it, he's right on target with ``whether and how __iadd__
> is implemented''  It's true that you can't expect to see immutable
> objects modified, a contradiction in terms, but you certainly can
> implement a mutable object that reassigns to the left hand side.
> So mutability isn't the real issue (as usual.)

I'm not sure I'm following what you mean. Do you mean you think that:

>>> x += y

should simply be a shortcut for:

>>> x = x + y

with mutable objects?

This doesn't make sense to me. 'iadd' or, "in-place add", is fairly clear in
meaning. It means the LHS should add the RHS to *itself*. In the case of
immutable objects this simply can't occur and so the result is simply a
re-assignment. With mutable objects, they should certainly modify
themselves.

The point is that in-place add can be implemented efficiently for mutable
objects where the intended action was to mutate the original. For example,
in the case of lists, you might find people writing:

>>> xs = xs + ys

This is inefficient and should of course be written as:

>>> xs.extend( ys )

But in-place add provides a simpler syntax for this action that retains the
operator of the original:

>>> xs += ys

This is especially important where you might be dealing with arithmetic
operations on large matrices. It's clumsy in the extreme to have to write:

>>> m1.multiplyBy( m2 )

when you really want to write:

>>> m1 *= m2

These semantics would be familiar to anyone from C++ and I'm sure they are
exactly what was intended by the original addition of the in-place
operators.

Therefore the difference in behaviour seen is entirely related to
mutability. If the object is mutable, it should be mutated.

Jonathan




More information about the Python-list mailing list