Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the small number cache defined in Python specification or is it an implementation detail?

Python seems to have a so called "small number cache" for numbers in the range -5 to 256. We can demonstrate that with the following program:

for i in range(-7, 258):
    if id(i) == id(i + 0):
        print(i, "is cached")
    else:
        print(i, "is not cached")

The output is

-7 is not cached
-6 is not cached
-5 is cached
-4 is cached
[...]
255 is cached
256 is cached
257 is not cached

I wonder whether that's defined in the Python specification or it's an implementation detail.

like image 922
Thomas Weller Avatar asked Sep 07 '25 21:09

Thomas Weller


1 Answers

It's an implementation detail: chapter 3.1 of the Python language reference (all versions, from 2.7 through 3.9) says:

for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value

and

E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation

(emphasis mine)

The Python/C API reference also mentions it

The current implementation keeps an array of integer objects for all integers between -5 and 256,

(emphasis mine) which is also quite clear that this might change in the future.

like image 105
Thomas Weller Avatar answered Sep 09 '25 11:09

Thomas Weller