【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我一直认为if not x is None
版本更清楚,但谷歌的风格指南和PEP-8都使用, if x is not None
。 是否存在任何轻微的性能差异(我假设没有),是否存在任何一个真正不合适的情况(使另一个成为我公约的明显赢家)?*
*我指的是任何单身人士,而不仅仅是None
。
...比较像无的单身人士。 使用是否。
#1楼
谷歌和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中查看哪些文字被评估为True
或False
:
编辑以下评论:
我刚做了一些测试。 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
。 我纠正了。 谢谢bukzor。
但是,我的回答仍然是: if x is not None
使用常规 。 :]
#2楼
if not x is None
更类似于其他编程语言,但if x is not None
, if x is not None
对我来说肯定听起来更清楚(并且在语法上更正确)。
这说对我来说似乎更偏向于它。
#3楼
代码应该首先编写为程序员可以理解,然后编译器或解释器编写。 “不是”构造比“不是”更接近英语。
#4楼
没有性能差异,因为它们编译为相同的字节码:
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
那么就没有歧义。
#5楼
在is not
运营商优于否定的结果is
文体上。 “ if x is not None:
”读取就像英语,但“ if not x is None:
”需要理解运算符优先级,而不是像英语那样读。
如果有性能差异我的钱是is not
,但是这几乎可以肯定是不喜欢这种技术决定的动机。 它显然是依赖于实现的。 既然is
不可覆盖的,那么无论如何都应该很容易优化任何区别。
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3147863