在 Python 中,哪些值整数停止被缓存和重用?
Since which value integers stop being cached and reused in Python?
在Python 3:
>> X = 42
>> Y = 42
>> X is Y
True
>> X = 2 ** 20
>> Y = 2 ** 20
>> X is Y
False
>> X = 2 ** 2
>> Y = 2 ** 2
>> X is Y
True
当我声明 "X is Y" 时,我开始得到 False 而不是 True 的整数的精确值是多少? (假设我是 运行 标准 Python 3 )。
这是 interpreter 依赖的(即没有规范要求这种缓存)。但据我所知,python
解释器有一个整数缓存,最大为 256。此外,不超过 -5 的值也会被缓存。所以 范围是 -5 到 256 (都包括在内),就像写在 documentation:
The current implementation keeps an array of integer objects for all integers between -5 and 256 (..)
因此最好永远不要使用引用相等性 来检查两个整数是否相等,总是使用==
。如果您将 int
与 numpy int16
进行比较,这也很有用。如果您使用参考检查,以下将失败:
>>> np.int16(12) is 12
False
>>> np.int16(12) == 12
True
在Python 3:
>> X = 42
>> Y = 42
>> X is Y
True
>> X = 2 ** 20
>> Y = 2 ** 20
>> X is Y
False
>> X = 2 ** 2
>> Y = 2 ** 2
>> X is Y
True
当我声明 "X is Y" 时,我开始得到 False 而不是 True 的整数的精确值是多少? (假设我是 运行 标准 Python 3 )。
这是 interpreter 依赖的(即没有规范要求这种缓存)。但据我所知,python
解释器有一个整数缓存,最大为 256。此外,不超过 -5 的值也会被缓存。所以 范围是 -5 到 256 (都包括在内),就像写在 documentation:
The current implementation keeps an array of integer objects for all integers between -5 and 256 (..)
因此最好永远不要使用引用相等性 来检查两个整数是否相等,总是使用==
。如果您将 int
与 numpy int16
进行比较,这也很有用。如果您使用参考检查,以下将失败:
>>> np.int16(12) is 12
False
>>> np.int16(12) == 12
True