inconsistency with += between different types ?
donn at u.washington.edu
Tue Aug 6 00:41:43 CEST 2002
Quoth Jonathan Hogg <jonathan at onegoodidea.com>:
| 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
I guess, but that's up to the implementor of the object. My point
is that the first order cause of the effect he noticed is, as he
surmised, that __iadd__ behaves differently. This way of thinking
about it is less prone to the frailties of wishful thinking.
It is indeed useful to recognize that some kinds of objects are
immutable in Python, and that this poses a problem for an operation
that's supposed to modify the LHS. The resolution is arbitrary,
though - should the result be re-assignment, or should immutable
objects just not support that operation?
Donn Cave, donn at u.washington.edu
| 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
| Therefore the difference in behaviour seen is entirely related to
| mutability. If the object is mutable, it should be mutated.
More information about the Python-list