[Tutor] Why does CPython cache small integers "asymmetrically"?

Peter Otten __peter__ at web.de
Sat May 29 04:11:16 EDT 2021


On 28/05/2021 02:13, boB Stepp wrote:
> On Thu, May 27, 2021 at 6:45 PM Cameron Simpson <cs at cskk.id.au> wrote:
>>
>> On 27May2021 13:37, Cameron Simpson <cs at cskk.id.au> wrote:
>>> The constants themselves seem to be here:
>>>     https://github.com/python/cpython/blob/3e7ee02327db13e4337374597cdc4458ecb9e3ad/Include/internal/pycore_interp.h#L211
>>
>> On reflection, these might just be the interned ints: some _precomputed_
>> cached ints :-) The larger range of cached int boB reports would be a
>> wider range implemented programmatically at runtime.
> 
> Actually the link you provide agrees almost exactly with the range I
> discovered of -4 to 256.  A bit farther along in the source you link
> to is a comment which says:
> 
> /* Small integers are preallocated in this array so that they
> can be shared.
> The integers that are preallocated are those in the range
> -_PY_NSMALLNEGINTS (inclusive) to _PY_NSMALLPOSINTS (not inclusive).
> */
> 
> Where you linked these constants were set to 5 and 257 respectively.
> The upper end I discovered via the interpreter agrees exactly since
> 257 is not included according to this comment.  However, I am puzzled
> by the negative end as -5 was *not* cached, but the comment says it is
> inclusively included.  So there is an off-by-one error here with what
> I observed in the interpreter and what the comment claims.  I tried to
> puzzle out the code, but was unsuccessful, wondering why they
> apparently they had two extra slots in the array created to store
> these cached integers.

I cannot confirm your findings:

 >>> sys.version
'3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 16:33:24) [MSC v.1928 32 bit 
(Intel)]'

 >>> x = -5
 >>> y = -5
 >>> x is y
True
 >>> x = -6
 >>> y = -6
 >>> x is y
False

 >>> x = 256
 >>> y = 256
 >>> x is y
True
 >>> x = 257
 >>> y = 257
 >>> x is y
False

i. e. the precomputed integers are in range(-5, 257) as the constants 
suggest. Maybe you are using an older version of the interpreter?

I think I remember that the lower bound used to be -2 in Python 2...




More information about the Tutor mailing list