使用 if x is not None 還是if not x is None呢?
谷歌的風格指南和PEP-8都使用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。所以if x is not y就沒有這些歧義。
以上就是使用 if x is not None 還是if not x is None的詳細內容,更多請關注php中文網其它相關文章!
本文原創發布php中文網,轉載請注明出處,感謝您的尊重!