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.
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
Using not x can cause unwanted results.
See below:
>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0] # You don't want to fall in this one.
>>> not x
False
You may be interested to see what literals are evaluated to True or False in Python:
- Truth Value Testing
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:
>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False
Therefore, not x is None is just, in my honest opinion, best avoided.
More edit:
I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)
This means 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. :]
Is there any downside of using if x / if not x versus if x is None / if x is not None ?
Why is "not None" true?
What's the most pythonic way of checking if variable is None or empty string ""?
What's the difference between != and is not?
Videos
I prefer the former because it's obviously shorter... reads better. Also, I can check whether a collection or a string is empty the same way (because it checks whether x evaluates to False).
I think the only disadvantage might be for variables of type e.g. int | None and when program's behaviour must be different for value 0 and for None. In such case, obviously, one should use if x is None.
>>>print(not None) True