之前的开发者在代码中留下了一个非常奇怪的not x is None yoda 条件:
>>> x = None
>>> not x is None
False
>>> x = 1
>>> not x is None
True
经过一些测试,我的输出似乎与 x is not None 相同。
>>> x = None
>>> not x is None
False
>>> x is not None
False
>>> x = 1
>>> not x is None
True
>>> x is not None
True
not x is None 是否总是等同于x is not None?
要分解条件,是 not (x is None) 还是 (not x) is None?或者前者总是等同于后者?
请您参考如下方法:
因为 is 比 not 有更高的优先级,所以表达式是等价的:
如果 x = None: x is None 的计算结果为 True,而 not x is None 的计算结果为 False 如果 x = 1: x is None 的计算结果为 False,而 not x is None 的计算结果为 True
如果 x = None: x 不是 None 计算结果为 False 如果 x = 1: x is not None 的计算结果为 True。
因此,即使操作在句法上不等价,结果也是等价的。
这是 not x is None 的 AST:
这是 x is not None 的 AST:
从第二张图中可以看出,内部节点是比较节点,因此 x is None 在 not 之前计算。
关于表达式的实际评估,似乎 python 为两者创建了相同的字节码。在这个例子中可以看出:
def foo(x):
x is not None
def bar(x):
not x is None
import dis
dis.dis(foo)
dis.dis(bar)
两者都产生:
0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (None)
6 COMPARE_OP 9 (is not)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
