Compound Assignment Operators ( +=, *=, etc...)
Tim Peters
tim_one at email.msn.com
Sun Aug 15 22:31:24 EDT 1999
>> ... does
>>
>> z = x
>> x += y
>> print z
>>
>> mean
>>
>> x = x + y # x is now bound to an entirely different object
>> # and the old x is printed
>>
>> or
>>
>> x.extend(y) # x is still the same object, but mutated
>> # and the new x is printed
>>
>> ? The resulting *values* compare equal either way, but there are
>> differences in efficiency and effects on object identity.
[Andrew McDowell]
> I don't see where the "non-obviousness" comes into play...
> (maybe that's why it's not obvious <wink>)
In that reasonable people can (& do) expect either behavior.
> Why would you confuse x += y (which would seem to imply the
> former) to mean x.extend(y) ?
Efficiency; and, to half the reasonable people in the world, obviousness
<wink>.
> It _is_ and assignment statement after all..
That's my mild preference, and it's easier to implement that way; but some
reasonable people want it the other way. Consider the NumPy extension,
where "x" can denote a matrix with millions of elements and consuming many
Mb of storage. There you may desperately not want e.g.
x += 1
to create an entirely new similar-sized matrix, yet still want the economy
of expression. Guido's preferred scheme caters to either behavior.
> Not to touch on a sore topic, but hop over to comp.lang.perl and
> check out the (rather long and heated) comparison of perl and python.
So *that's* what it is -- I thought it was a flame war.
> The lack of these statements is causing quite a bit of a stir.
I expect you could post "have a nice day!" to that thread and also "cause"
quite a bit of a stir. Flame wars aren't "about" the topics being toasted,
y'know <0.1 wink>.
>> ... it's up to x.__addeq__(y) to decide what "+=" (& so on) means.
> Why addeq?? Why not just add?
So that it's *possible* for the implementation of x's type to arrange for
y = x + 1
to create a new object but for
x += 1
not to. If you don't want to allow for mutation, __addeq__ isn't needed
(and you can find an implementation sketch in DejaNews for this case -- it's
easy to implement in Python's front end).
lettuce-should-never-be-chewed-twice-ly y'rs - tim
More information about the Python-list
mailing list