What happens behind the scenes when python adds small ints?
What happens behind the scenes when python adds small ints?
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 Question
01:09 Accepted answer (Score 17)
02:25 Answer 2 (Score 20)
03:13 Answer 3 (Score 2)
03:34 Thank you
--
Full question
https://stackoverflow.com/questions/6101...
Accepted answer links:
[Source]: http://docs.python.org/c-api/int.html#Py...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #integer #cpython
#avk47
ANSWER 1
Score 20
You've fallen into a not uncommon trap:
id(2 * x + y) == id(300 + x)
The two expressions 2 * x + y and 300 + x don't have overlapping lifetimes. That means that Python can calculate the left hand side, take its id, and then free the integer before it calculates the right hand side. When CPython frees an integer it puts it on a list of freed integers and then re-uses it for a different integer the next time it needs one. So your ids match even when the result of the calculations are very different:
>>> x, y = 100, 40000
>>> id(2 * x + y) == id(300 + x)
True
>>> 2 * x + y, 300 + x
(40200, 400)
ACCEPTED ANSWER
Score 17
Python keeps a pool of int objects in certain numbers. When you create one in that range, you actually get a reference to the pre-existing one. I suspect this is for optimization reasons.
For numbers outside the range of that pool, you appear to get back a new object whenever you try to make one.
$ python
Python 3.2 (r32:88445, Apr 15 2011, 11:09:05)
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 300
>>> id(x)
140570345270544
>>> id(100+200)
140570372179568
>>> id(x*2)
140570345270512
>>> id(600)
140570345270576
PyObject* PyInt_FromLong(long ival) Return value: New reference. Create a new integer object with a value of ival.
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
emphasis mine
ANSWER 3
Score 2
AFAIK, id has nothing to do with the size of the parameter. It MUST return a life-time unique identifier, and it CAN return the same result for two different parameters, if they do not exist concurrently.