Search code examples
python-3.xcachingintegerinternals

Since which value integers stop being cached and reused in Python?


In Python 3:

>> X = 42
>> Y = 42
>> X is Y
True

>> X = 2 ** 20
>> Y = 2 ** 20
>> X is Y
False

>> X = 2 ** 2
>> Y = 2 ** 2
>> X is Y
True

What is the precise value for integers since which I start getting False instead of True when I state "X is Y"? ( Assuming I'm running standard Python 3 ).


Solution

  • This is interpreter dependent (i.e. there are no specifications that require such caching). But as far as I know the python interpreter has a cache for integers up to and including 256. Furthermore values up to and including -5 are cached as well. So the range is -5 to 256 (both included), like written in the documentation:

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

    You thus better never use reference equality to check whether two integers are equal, always use ==. This is also useful if you for instance would compare an int against a numpy int16. If you use reference checks, the following will fail:

    >>> np.int16(12) is 12
    False
    >>> np.int16(12) == 12
    True