patternpythonCriticalCanonical
Python `if x is not None` or `if not x is None`?
Viewed 0 times
nonepythonnot
Problem
I've always thought of the
*I'm referring to any singleton, rather than just
...to compare singletons like
None. Use is or is not.
if not x is None version to be more clear, but Google's style guide and PEP-8 both use if x is not None. Are there any minor performance differences (I'm assuming not), and is there any case where one really doesn't fit (making the other a clear winner for my convention)?**I'm referring to any singleton, rather than just
None....to compare singletons like
None. Use is or is not.
Solution
There's no performance difference, as they compile to the same bytecode:
Stylistically, I try to avoid
>>> 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_VALUEStylistically, 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.Code Snippets
>>> 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_VALUEContext
Stack Overflow Q#2710940, score: 1325
Revisions (0)
No revisions yet.