今天爱分享给大家带来python使用 ‘if x is not None’ 还是’if not x is 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’ 就不会有歧义
最佳实践
if x is not None:
# Do something about x