我可以使用 « is » 来与静态变量进行比较吗?

Can I use « is » to compare against static variables?

Python 的 PEP 435 about the enum module says that enumerators should be compared with is 而不是通常的 ==。我猜这是因为枚举成员是静态的,永远不会改变,所以这是有道理的。

出于兼容性原因,我正在使用Python 2.7.9,我不想为项目引入太多新库,所以我不打算使用Python 2.7 enum 模块的 .9 端口。因此,我改用更简单的枚举形式:

class Color(object):
    red = 1
    green = 2
    blue = 3

这样的话,用is来比较还好吗?更一般地说,是否可以将已知在程序生命周期内不会更改的静态 class 变量与 is 而不是 == 进行比较,而不管它们的类型如何?

注意: 我认为只有静态变量的名称将用于 assignment/comparison,而不是它的值。

可能有效,因为 CPython 对 [-5, ..., 256] 中的数字使用相同的地址(它们永远不会重新创建):

>>> (-5 + 0) is -5
True
>>> (-6 + 0) is -6
False
>>> (256 + 0) is 256
True
>>> (257 + 0) is 257
False

但它依赖于实现,这不是一件好事。

为什么不使用 == 呢?

可以吗? - 小整数在 CPython 中被保留,所以无论你得到什么,例如x = 2 来自,x is Color.green 将评估 True

应该吗? 没有。一方面,它在概念上没有意义——你真的关心它们是否是完全相同的对象(identityis),或者只是它们是否具有相同的值(相等==)?如果这些值来自 class 本身以外的其他地方怎么办,例如数据库或用户输入?另一方面,小整数的驻留是 实现细节 ,因此不应依赖。

More generally, is it ok to compare static class variables that are known not to change during the lifetime of the program with is instead of ==, regardless of their type?

,因为无论它们是否 "static":

都可能失败
>>> class Demo(object):
    class_attr = "some string"


>>> "some string" is Demo.class_attr
False