In Python, when checking if a variable is not None, is it better to use if x is not None or if not x is None?
I’ve always thought that if not x is None is clearer, but both Google’s style guide and PEP-8 recommend using if x is not None. Are there any minor performance differences between these two approaches? Additionally, is there any scenario where one is clearly preferable over the other for checking if a variable is not None, or any singleton?
Hello Sakshi,
There is no performance difference between if x is not None and if not x is None, as both 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
However, stylistically, it’s better to use if x is not None. The expression not x is None might be misread as (not x) is None, whereas x is not None is clearer and unambiguous. This helps ensure that the code is easy to read and understand.
Hello Sakshikuchroo,
Both Google’s style guide and Python’s PEP-8 recommend the best practice of using if x is not None:
if x is not None:
# Do something with x
Using not x can lead to unintended results, as it evaluates to False for many values that are not None. For example:
x = 1
not x
False
x = [1]
not x
False
x = 0
not x
True
x = [0] # This evaluates to False, which might be misleading.
not x
False
In Python, different literals and values are evaluated as either True or False. It’s important to use is not None to avoid ambiguity and ensure your code behaves as expected.
Hello Sakshi,
The choice between x is not None and not x is None boils down to simplicity and convention.
There is no technical advantage to either approach; both compile to the same bytecode. However, x is not None is the widely accepted standard. It’s the convention that most Python users follow, which makes it the clear choice. Using x is not None ensures that your code is immediately understandable to all Python developers, regardless of their background or native language.
In short, adhering to common practices helps maintain readability and consistency in code. It’s best to follow established conventions rather than opting for less common syntax, as it minimizes confusion and promotes clarity.