Python`如果x不是None`或`如果不是x是None? [英] Python `if x is not None` or `if not x is None`?
问题描述
我一直认为如果不是x是无
版本更清楚,但Google的样式指南和 PEP-8 都使用如果x不是无
。是否有任何细微的性能差异(我假设不是),是否有一个真的不适合(使另一个明显胜出我的会议)?
I've always thought of the if not x is None
version to be more clear, but Google's style guide and PEP-8 both use if x is not None
. Is there any minor performance difference (I'm assuming not), and is there any case where one really doesn't fit (making the other a clear winner for my convention)?*
*我指的是任何单例,而不是无
。
*I'm referring to any singleton, rather than just None
.
...比较单例如
无。使用是或不是。
...to compare singletons like None. Use is or is not.
推荐答案
没有性能差异, bytecode:
There's no performance difference, as they compile to the same bytecode:
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
在文体上,我试图避免不是x是y
。虽然编译器总是将它视为 not(x is y)
,一个人类读者可能会误认为(not x)是y
。如果我写
x不是y
,则没有歧义。
Stylistically, I try to avoid not x is y
. Although the compiler will always treat it as not (x is y)
, a human reader might misunderstand the construct as (not x) is y
. If I write x is not y
then there is no ambiguity.
这篇关于Python`如果x不是None`或`如果不是x是None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!