Is behavior of += intentional for int?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 29 21:03:23 CEST 2009


On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote:

> I thought that int as object will stay the same object after += but with
> another integer value. My intuition said me that int object which
> represent integer value should behave this way.

If it did, then you would have this behaviour:


>>> n = 3                     # bind the name n to the object 3
>>> saved_id = id(n)          # get the id of the object
>>> n += 1                    # add one to the object 3
>>> assert n == 4             # confirm that it has value four
>>> assert id(n) == saved_id  # confirm that it is the same object
>>> m = 3                     # bind the name m to the object 3
>>> print m + 1               # but object 3 has been modified
5

This would be pretty disturbing behaviour, and anything but intuitive.

Fortunately, Python avoids this behaviour by making ints immutable. You 
can't change the object 3 to have any other value, it will always have 
value three, and consequently n+=1 assigns a new object to n.


-- 
Steven



More information about the Python-list mailing list