Is behavior of += intentional for int?

Carl Banks pavlovevidence at gmail.com
Wed Sep 2 01:43:06 CEST 2009


On Sep 1, 10:40 am, Piet van Oostrum <p... at cs.uu.nl> wrote:
> >>>>> zaur <szp... at gmail.com> (z) wrote:
> >z> On 29 авг, 16:45, zaur <szp... at gmail.com> wrote:
> >>> Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> >>> [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> >>> Type "copyright", "credits" or "license()" for more information.>>> a=1
> >>> >>> x=[a]
> >>> >>> id(a)==id(x[0])
> >>> True
> >>> >>> a+=1
> >>> >>> a
> >>> 2
> >>> >>> x[0]
>
> >>> 1
>
> >>> I thought that += should only change the value of the int object. But
> >>> += create new.
> >>> Is this intentional?
> >z> As a result of this debate is not whether we should conclude that
> >z> there should be two types of integers in python: 1) immutable numbers,
> >z> which behave as constant value; 2) mutable numbers, which behave as
> >z> variable value?
>
> 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.

I wouldn't agree with that terminology or logic.

First of all "mutable number" is really just a short way to say
"mutable number object".  A number object in Python is not a number,
it's just a representation of a number.  Even if numbers are immutable
by nature, an object representing a number need not be.

And if your number object is mutable, it does not make that object a
container, at least not what I would call a container.  A container
you have to dereference somehow to get at the object inside, whereas a
mutable number object you don't dereference: it acts like number as-
is.

IOW, the first example below is a container, the second is not:

num = [2]
num[0] += 3

num = mutable_int(2)
num += 3

(If you want to call the mutable number a container anyway, fine with
me, I am not here to bicker.)  A container is sufficient to get a
layer of indirection if that's what you want the mutable number for.

However, the mutable number has a performance advantage over using a
container: it avoids the overhead of creating a new object.  If you
were using += in a loop like this, it could turn out to be significant
savings.  But since that's not common in Python I'd have to agree that
this optimization opportunity is best done with a third-party C-
extension, and not the standard library.


Carl Banks



More information about the Python-list mailing list