Is behavior of += intentional for int?
Piet van Oostrum
piet at cs.uu.nl
Wed Sep 2 10:45:09 CEST 2009
>>>>> Carl Banks <pavlovevidence at gmail.com> (CB) wrote:
>CB> On Sep 1, 10:40 am, Piet van Oostrum <p... at cs.uu.nl> wrote:
>>> Numbers are immutable by nature (math). The number 3.14 remains 3.14
>>> whatever you try to do with it. What you call an immutable number is in
>>> fact a container that contains a number.
>CB> I wouldn't agree with that terminology or logic.
>CB> First of all "mutable number" is really just a short way to say
>CB> "mutable number object". A number object in Python is not a number,
>CB> it's just a representation of a number. Even if numbers are immutable
>CB> by nature, an object representing a number need not be.
Yes, that remark I made was more on the meta level.
>CB> And if your number object is mutable, it does not make that object a
>CB> container, at least not what I would call a container. A container
>CB> you have to dereference somehow to get at the object inside, whereas a
>CB> mutable number object you don't dereference: it acts like number as-
If you read the OP, that was exactly what the OP (human) expected. That
the list would contain some kind of reference to the number. And then of
course you would have to dereference it to get the number.
>CB> IOW, the first example below is a container, the second is not:
>CB> num = 
>CB> num += 3
>CB> num = mutable_int(2)
>CB> num += 3
>CB> (If you want to call the mutable number a container anyway, fine with
>CB> me, I am not here to bicker.) A container is sufficient to get a
>CB> layer of indirection if that's what you want the mutable number for.
>CB> However, the mutable number has a performance advantage over using a
>CB> container: it avoids the overhead of creating a new object. If you
>CB> were using += in a loop like this, it could turn out to be significant
>CB> savings. But since that's not common in Python I'd have to agree that
>CB> this optimization opportunity is best done with a third-party C-
>CB> extension, and not the standard library.
That's an implementation detail.
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org
More information about the Python-list