How to check 'NONE' in condition in python?

+1 vote
asked Aug 6, 2016 by Hitesh Garg (799 points)  

As per my understanding there are two possible ways of checking None in python -

  1. if x is not None
  2. if not x is None

Which one of them is better and what basically difference between the two? Is there any performance difference between the two or is there any situation in which only one of them can be used and not the other?

1 Answer

0 votes
answered Aug 9, 2016 by Rahul Singh (682 points)  

According to the best practice by google and python one should use the first one i.e. if x is not None.

And there is no performance difference as in the code below one can observe that both the functions are compiled to the same output.

>>> def foo2(x):
...     return x is not None

>>> dis.dis(foo2)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

>>> def foo(x):
...     return not x is None
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE

There is no issue on compiler side in both the syntax but for a human reader there could be a problem if read as if (not x) is None.

Further we can also look for the use of is keyword -
Since None is the sole singleton object of NoneType in Python, we can use is operator to check if a variable has None in it or not.
Quoting from is docs,
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

According to Python's Coding Style Guidelines - PEP-008 -

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