[Tutor] Python cashes low integers? How? Where?
Kalle Svensson
kalle at lysator.liu.se
Mon Aug 9 01:15:41 CEST 2004
Hi!
[Dick Moores]
> >>> a = 4
> >>> b = 1 + 3
> >>> a is b
> True
...
> OK. Now, this intrigued me. Where does Python do this cashing? Not
> in my computer's memory, because rebooting doesn't change the above
> results. So where?
Indeed in your computer's memory, but the cache is not persistent
between reboots or even Python invocations.
The line 'a = 4' creates an integer object with the value 4 (let's
call it <int 4>), and since 4 is less than some limit, the object is
cached. 'a' now points to <int 4> and the integer cache contains one
object, the same <int 4>.
Next, the line 'b = 1 + 3' creates two integer objects, <int 1> and
<int 3>. They are also cached. They are then added together. Since
the result is 4, no new integer object is created but a reference to
the cached <int 4> is returned and 'b' is made to point to it.
Thus 'a is b' comes to be true. The integer cache now contains
<int 1>, <int 3> and <int 4>. The next time you start Python, the
integer cache is empty again.
Hope this helps!
Peace,
Kalle
--
http://juckapan.org/~kalle/
http://laxmasteriet.se/04-05/
More information about the Tutor
mailing list