Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Integer caching in Python

📅 2012-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

When a Python program assigns integers to variables, thus giving a name to a value, integer objects need to be created for them. Integers like 0, -1 or small integers are very common in programs. For integer object creation, use and destruction to be efficient for these common values, these objects are created only once and cached to be used for any variable that need such a value.

The range of integers that are cached by Python is specific to the implementation. But, this can be discovered easily by using the is operator, which returns True is two names are refer to the same object.

# Python caches a small range of integers (objects)
# This is implementation specific and can be discovered easily

import platform

cacheBegin, cacheEnd = 0, 0

for i in range( -500, 0 ):
    if i is int(str(i)):
        cacheBegin = i
        break

for i in range( cacheBegin, 500 ):
    if i is not int(str(i)):
        cacheEnd = i - 1
        break

print( "Python version: {} implementation: {}".format( platform.python_version(), platform.python_implementation() ) )
print( "This implementation caches integers {} to {}".format( cacheBegin, cacheEnd ) )

On my Python 3.2 64-bit CPython implementation, the range of integers that are cached seems to be -5 to 256.

Tried with: Python 3.2 64-bit on Windows 7