Python规范中定义的小数缓存还是实现细节?
Is the small number cache defined in Python specification or is it an implementation detail?
Python 似乎有一个所谓的“小数字缓存”,用于存储 -5 到 256 范围内的数字。我们可以用以下程序证明这一点:
for i in range(-7, 258):
if id(i) == id(i + 0):
print(i, "is cached")
else:
print(i, "is not cached")
输出为
-7 is not cached
-6 is not cached
-5 is cached
-4 is cached
[...]
255 is cached
256 is cached
257 is not cached
我想知道这是在 Python 规范中定义的还是一个实现细节。
这是一个实现细节:chapter 3.1 of the Python language reference(所有版本,从 2.7 到 3.9)说:
for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value
和
E.g., after a = 1; b = 1
, a
and b
may or may not refer to the same object with the value one, depending on the implementation
(强调我的)
The current implementation keeps an array of integer objects for all integers between -5 and 256,
(强调我的)这也很清楚,这可能会在未来发生变化。
Python 似乎有一个所谓的“小数字缓存”,用于存储 -5 到 256 范围内的数字。我们可以用以下程序证明这一点:
for i in range(-7, 258):
if id(i) == id(i + 0):
print(i, "is cached")
else:
print(i, "is not cached")
输出为
-7 is not cached
-6 is not cached
-5 is cached
-4 is cached
[...]
255 is cached
256 is cached
257 is not cached
我想知道这是在 Python 规范中定义的还是一个实现细节。
这是一个实现细节:chapter 3.1 of the Python language reference(所有版本,从 2.7 到 3.9)说:
for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value
和
E.g., after
a = 1; b = 1
,a
andb
may or may not refer to the same object with the value one, depending on the implementation
(强调我的)
The current implementation keeps an array of integer objects for all integers between -5 and 256,
(强调我的)这也很清楚,这可能会在未来发生变化。