Hướng dẫn python check if none

Out of these not None tests.

if val != None:

if not (val is None):

if val is not None:

Which one is preferable, and why?

Hướng dẫn python check if none

lospejos

1,9683 gold badges19 silver badges33 bronze badges

asked Oct 19, 2010 at 3:20

prosseekprosseek

174k200 gold badges549 silver badges848 bronze badges

2

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. is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program, is is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".

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.

answered Oct 19, 2010 at 3:24

9

From, Programming Recommendations, 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 is essential reading for any Python programmer.

answered Oct 19, 2010 at 3:35

Hướng dẫn python check if none

johnsywebjohnsyweb

132k23 gold badges178 silver badges239 bronze badges

0

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

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

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

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

answered Oct 20, 2013 at 19:44

SheetJSSheetJS

21.7k12 gold badges63 silver badges75 bronze badges

2

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

answered Oct 19, 2010 at 3:23

1