Integer caching in Python

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
for i in range( cacheBegin, 500 ):
if i is not int(str(i)):
cacheEnd = i 1
print( "Python version: {} implementation: {}".format( platform.python_version(), platform.python_implementation() ) )
print( "This implementation caches integers {} to {}".format( cacheBegin, cacheEnd ) )

view raw
hosted with ❤ by GitHub

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

2 thoughts on “Integer caching in Python

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.