简体   繁体   English

Python 小 integer 缓存:分配多个值时有什么不同?

[英]Python small integer cache: what's different when assigning multiple values?

I'm aware of the CPython implementation that holds a small integer cache in the [-5, 256] range, so I understand that a=2 and b=2 will refer to the same memory address (thus causing a is b to return true. Also, if I store a number higher than 256 I should obtain different memory addresses, as follows:我知道 CPython 实现在 [-5, 256] 范围内保存一个小的 integer 缓存,所以我知道a=2b=2将引用相同的 memory 地址(因此导致a is b返回是的。此外,如果我存储一个大于 256 的数字,我应该获得不同的 memory 地址,如下所示:

>>> x=500
>>> y=500
>>> x is y
False

However, this is where I get confused:然而,这是我感到困惑的地方:

>>> x,y=500,500
>>> x is y
True

Can anyone explain why this happens, or at least what's different when storing values separately as opposed to storing them both at once?任何人都可以解释为什么会发生这种情况,或者至少在分别存储值而不是同时存储它们时有什么不同?

Whenever in one of the compiling steps the language finds out an easy optimization to take place, it does so.每当在其中一个编译步骤中,语言发现可以进行简单的优化时,它就会这样做。

In this case, when compiling the line a, b = 500, 500 it will create the 500 as a constant in the current context, in the same compilation step - when it sees the second 500 - it is a constant that already exists, so the compiler just reuses it.在这种情况下,当编译行a, b = 500, 500时,它将在当前上下文中创建 500 作为常量,在相同的编译步骤中 - 当它看到第二个 500 - 它是一个已经存在的常量,所以编译器只是重用它。

Note that if the same optimization was in another layer of the compiler, it would trigger across the number being input in different lines - this behavior should not be asserted as something to be relied upon.请注意,如果相同的优化在编译器的另一层进行,它会触发不同行中输入的数字——不应断言此行为是可靠的。

Just as in this case, there are lots of small optimizations that can take place, but are not part of the language specification: just as the small integer cache, this is an implementation specific optimization.就像在这种情况下,可以进行许多小的优化,但不是语言规范的一部分:就像小的 integer 缓存一样,这是一个特定于实现的优化。

In particular, one should never write code that relies on these optimizations - comparing numbers should always be done with == , even in the case of the well-known small integers, as they not only will be different across different Python implementations, but also, they could change without notice in the same implementation.特别是,永远不要编写依赖于这些优化的代码 - 比较数字应该始终使用==完成,即使是众所周知的小整数,因为它们不仅在不同的 Python 实现中会有所不同,而且,它们可以在同一实现中更改,恕不另行通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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