简体   繁体   中英

Python macros, NSMALLPOSINTS vs NSMALLNEGINTS

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.

for the question:

If we assume we are using a CPython implementation of Python3 with default options how many int objects have been created and are still in memory when we execute print("I")

I believe the answer should be 262 if we include 0.

This is a reply to EkaterinaKalache. I would have used direct reply, but my reputation is low.

correct me if I am wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM