Python `if x is not None` or `if not x is None`? [closed]
There's no performance difference, as they compile to the same bytecode:
import dis dis.dis("not x is None") 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (None) 4 COMPARE_OP 9 (is not) 6 RETURN_VALUE dis.dis("x is not None") 1 0 LOAD_NAME 0 (x) 2 LOAD_CONST 0 (None) 4 COMPARE_OP 9 (is not) 6 RETURN_VALUE
Stylistically, I try to avoid
not x is y, a human reader might misunderstand it as
(not x) is y. If I write
x is not y then there is no ambiguity.
Both Google and Python's style guide is the best practice:
if x is not None: # Do something about x
not x can cause unwanted results.
1not xFalsex = not xFalsex = 0not xTruex =  # You don't want to fall in this one.not xFalsex =
You may be interested to see what literals are evaluated to
False in Python:
Edit for comment below:
I just did some more testing.
not x is None doesn't negate
x first and then compared to
None. In fact, it seems the
is operator has a higher precedence when used that way:
0]not x is NoneTruenot (x is None)True(not x) is NoneFalsex[
not x is None is just, in my honest opinion, best avoided.
I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)
if x is not None has the exact result as
if not x is None. I stand corrected. Thanks bukzor.
However, my answer still stands: Use the conventional
if x is not None.