I've always thought of the
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. Is there any minor performance difference (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
...to compare singletons like None. Use is or is not.
There's no performance difference, as they compile to the same bytecode:
Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39) >>> import dis >>> def f(x): ... return x is not None ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE >>> def g(x): ... return not x is None ... >>> dis.dis(g) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 0 (None) 6 COMPARE_OP 9 (is not) 9 RETURN_VALUE
Stylistically, I try to avoid
not x is y. Although the compiler will always treat it as
not (x is y), a human reader might misunderstand the construct 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. See below:
>>> x = 1 >>> not x False >>> x =  >>> not x False >>> x = 0 >>> not x True >>> x =  # You don't want to fall in this one. >>> not x False
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:
>>> x  >>> not x is None True >>> not (x is None) True >>> (not x) is None False
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.