gpt4 book ai didi

Python `if x is not None` 还是 `if not x is None` ?

转载 作者:IT老高 更新时间:2023-10-28 12:00:24 30 4
gpt4 key购买 nike

我一直认为 if not x is None 版本更清楚,但 Google 的 style guidePEP-8两者都使用 if x is not None。是否存在任何细微的性能差异(我假设没有),是否有任何情况下一个确实不适合(使另一个明显成为我的大会的赢家)?*

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

...to compare singletons likeNone. Use is or is not.

最佳答案

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

>>> import dis
>>> dis.dis("not x is None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("x is not None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE

在风格上,我尽量避免 not x is y,人类读者可能会将其误解为 (not x) is y。如果我写 x is not y 那么就没有歧义了。

关于Python `if x is not None` 还是 `if not x is None` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2710940/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com