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

boB Stepp robertvstepp at gmail.com
Thu May 27 20:13:37 EDT 2021


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 guess I will never know the answer to how these values were chosen.
<sad face>

boB

> Still no deeper insights though.


More information about the Tutor mailing list