[Tutor] Python cashes low integers? How? Where?

Dick Moores rdm at rcblue.com
Mon Aug 9 08:49:50 CEST 2004


Kalle Svensson wrote at 16:15 8/8/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!

Sure did. Thanks very much.

BTW for me, the caching seems to be done for integers up to, but not 
including, 100.

If I could ask what seems to be a related question: On p. 85 Chun says, 
"Each object has associated with it a counter that tracks the total 
number of references that exist to that object. This number simply 
indicates how many variables are 'pointing to' any particular 
object."  However, he doesn't say how to find this number. Is there a way?

Thanks,

Dick Moores



More information about the Tutor mailing list