在 Python 中不是 None 测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3965104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:35:45  来源:igfitidea点击:

not None test in Python

pythonnonetype

提问by prosseek

Out of these not None tests.

在这些不是 None 测试中。

if val != None:

if not (val is None):

if val is not None:

Which one is preferable, and why?

哪一个更可取,为什么?

采纳答案by gotgenes

if val is not None:
    # ...

is the Pythonic idiom for testing that a variable is not set to None. This idiom has particular uses in the case of declaring keyword functions with default parameters. istests identity in Python. Because there is one and only one instance of Nonepresent in a running Python script/program, isis the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8under "Programming Recommendations".

是用于测试变量未设置为None. 在使用默认参数声明关键字函数的情况下,此习语具有特殊用途。is在 Python 中测试身份。因为None在运行的 Python 脚本/程序中存在一个且只有一个实例,所以这是is对此的最佳测试。正如Johnsyweb 所指出的,这在PEP 8 的“编程建议”下进行了讨论。

As for why this is preferred to

至于为什么这是首选

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

this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.

这只是Python禅的一部分:“可读性很重要”。好的 Python 通常接近好的伪代码

回答by Ignacio Vazquez-Abrams

Either of the latter two, since valcould potentially be of a type that defines __eq__()to return true when passed None.

后两者中的任何一个,因为val可能是定义__eq__()为在传递时返回 true的类型None

回答by Johnsyweb

From, Programming Recommendations, PEP 8:

来自,编程建议,PEP 8

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

Also, beware of writing if xwhen 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!

与像 None 这样的单例的比较应该总是用isor来完成is not,而不是等号运算符。

另外,if x当你真正想写的时候要小心if x is not None——例如,当测试一个默认为 None 的变量或参数是否被设置为其他值时。另一个值可能具有在布尔上下文中可能为 false 的类型(例如容器)!

PEP 8 is essential reading for any Python programmer.

PEP 8 是任何 Python 程序员的必备读物。

回答by SheetJS

The best bet with these types of questions is to see exactly what python does. The dismodule is incredibly informative:

这些类型问题的最佳选择是确切地了解 python 的作用。该dis模块提供了令人难以置信的信息:

>>> def f(val):
...   if val != None:
...     return True
...   return False
...
>>> def g(val):
...   if not (val is None):
...     return True
...   return False
...
>>> def h(val):
...   if val is not None:
...     return True
...   return False
...
>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (val)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               3 (!=)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_GLOBAL              1 (True)
             15 RETURN_VALUE

  4     >>   16 LOAD_GLOBAL              2 (False)
             19 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_FAST                0 (val)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_GLOBAL              1 (True)
             15 RETURN_VALUE

  4     >>   16 LOAD_GLOBAL              2 (False)
             19 RETURN_VALUE
>>> dis.dis(h)
  2           0 LOAD_FAST                0 (val)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 POP_JUMP_IF_FALSE       16

  3          12 LOAD_GLOBAL              1 (True)
             15 RETURN_VALUE

  4     >>   16 LOAD_GLOBAL              2 (False)
             19 RETURN_VALUE

Note that the last two cases reduce to the same sequence of operations (python reads not (val is None)and uses the is notoperator). The first uses the !=operator when comparing with None.

请注意,最后两种情况简化为相同的操作序列(python 读取not (val is None)并使用is not运算符)。第一个!=在与 None 比较时使用运算符。

As pointed out by other answers, using !=when comparing with None is a bad idea

正如其他答案所指出的,!=与 None 比较时使用是一个坏主意