不是Python中的None测试

2024-05-21 07:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在这些测试中没有一个测试。

if val != None:

if not (val is None):

if val is not None:

哪个更好,为什么?


Tags: noneifisnotval
3条回答

后两者之一,因为val可能是定义__eq__()的类型,以便在传递None时返回true。

if val is not None:
    # ...

是测试变量未设置为None的Pythonic习惯用法。这个习语在declaring keyword functions with default parameters的情况下有特殊的用途。is在Python中测试标识。因为运行的Python脚本/程序中只存在一个None实例,is是对此的最佳测试。作为Johnsyweb points out,这在PEP 8“编程建议”下讨论。

至于为什么这是首选

if not (val is None):
    # ...

这只是Zen of Python“可读性很重要”的一部分,好的Python通常接近好的pseudocode

来自,编程建议,PEP 8

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

PEP 8对于任何Python程序员来说都是必不可少的读物。

相关问题 更多 >