Python“如果x不是None”或者“如果x不是None”?

2024-03-28 21:11:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直认为if not x is None版本更清晰,但是Google的style guidePEP-8都使用if x is not None。有没有小的表现差异(我想没有),有没有一个真的不适合(使另一个明显的赢家为我的公约)?*

*我指的是任何单体,而不仅仅是None

...to compare singletons like None. Use is or is not.


Tags: to版本noneifisstylegooglenot
3条回答

Google和Python的风格指南都是最佳实践:

if x is not None:
    # Do something about x

使用not x可能会导致不需要的结果。见下文:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

您可能有兴趣查看在Python中计算为TrueFalse的文本:

在下面编辑评论:

我只是做了更多的测试。not x is None不会先否定x,然后再与None进行比较。实际上,这样使用时,is运算符的优先级似乎更高:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

因此,not x is None在我看来,最好避免。

更多编辑:

我只是做了更多的测试,可以确认bukzor的评论是正确的。(至少,我无法证明这一点。)

这意味着if x is not None的结果与if not x is None的结果完全相同。我坚持改正。谢谢布克佐尔。

然而,我的答案仍然是:使用传统的if x is not None:]

代码应该首先被程序员理解,其次是编译器或解释器。“不是”结构比“不是”更像英语。

没有性能差异,因为它们编译为相同的字节码:

Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39)
>>> import dis
>>> def f(x):
...    return x is not None
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE
>>> def g(x):
...   return not x is None
...
>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

在风格上,我尽量避免not x is y。尽管编译器总是将其视为not (x is y),但人类读者可能会误解该构造为(not x) is y。如果我写x is not y,那么就没有歧义。

相关问题 更多 >