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:
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
. :]