How NSMALLPOSINTS
, NSMALLNEGINTS
macros are used in python?
Is nsmallnegint
is in the range -5 to 0 and nsmallposint
is in the 0 to 256 range?
EDIT:
I am still unclear why NSMALLPOSINTS
, NSMALLNEGINTS
have those values.
How NSMALLPOSINTS
, NSMALLNEGINTS
macros are used in python?
Is nsmallnegint
is in the range -5 to 0 and nsmallposint
is in the 0 to 256 range?
EDIT:
I am still unclear why NSMALLPOSINTS
, NSMALLNEGINTS
have those values.
To answer my own question: those values are used, because they are most used integers!
To better understand how NSMALLPOSINTS
and NSMALLNEGINTS
work:
It is actually an array of 262 integers (most commonly used). And this structure is basically used to access these integers fast. They get allocated right when you initialize your NSMALLPOSINTS
and NSMALLNEGINTS
.
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
You're correct that the range is from -5 (inclusive) to 257 (non-inclusive). In the source code for the Python int object, there are macros defined called NSMALLPOSINTS and NSMALLNEGINTS.
Python source code for NSMALLPOSINTS and NSMALLNEGINTs
It turns out Python keeps an array of integer objects for “all integers between -5 and 256”. When we create an int in that range, we’re actually just getting a reference to the existing object in memory.
If we set x = 42, we are actually performing a search in the integer block for the value in the range -5 to +257. Once x falls out of the scope of this range, it will be garbage collected (destroyed) and be an entirely different object. The process of creating a new integer object and then destroying it immediately creates a lot of useless calculation cycles, so Python preallocated a range of commonly used integers.