[Python源码剖析]获取Python小整数集合范围
#!/usr/bin/env python
#-*- coding=utf-8 -*-
small_ints = dict()
for i in range(-10000,10000):
small_ints[i] = id(i)
for i in range(-10000,10000):
if id(i) != small_ints[i]:
del small_ints[i]
print("[%s, %s]"%(min(small_ints.keys()), max(small_ints.keys())))
在默认的官方下载的安装程序Python2.7 和Python3.6结果一样都是
[-5, 256]
Python源码Objects/intobject.c]中64-75行是
#ifndef NSMALLPOSINTS #define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5 #endif #if NSMALLNEGINTS + NSMALLPOSINTS > 0 /* References to small integers are saved in this array so that they can be shared. The integers that are saved are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */
默认设定为[-5,257), 需要改源码编译安装才能自定义这个小整数集合. Python是用对象池技术实现的. 具体继续看书了...


浙公网安备 33010602011771号