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.