0

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.

2 Answers2

1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yes, this is the issue where it was discussed to extend from [0,100] to [-5,256] : https://bugs.python.org/issue1436243 Related question : https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – matthieu Feb 12 '19 at 09:59
0

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.

  • 1
    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")` ? – Ekaterina Kalache Jun 30 '17 at 22:07
  • 1
    @EkaterinaKalache What exactly do you mean? If that is the only statement in your source code, then `261`(`abs(-5) + 256`) integer objects exist in memory. – Christian Dean Jun 30 '17 at 22:10
  • Thank you, Christian. It confirms that I understood it correctly. – Ekaterina Kalache Jun 30 '17 at 22:51