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 None
.
...to compare singletons like None. Use is or is not.
There's no performance difference, as they compile to the same bytecode:
Stylistically, I try to avoid
not x is y
. Although the compiler will always treat it asnot (x is y)
, a human reader might misunderstand the construct as(not x) is y
. If I writex is not y
then there is no ambiguity.The answer is simpler than people are making it.
There's no technical advantage either way, and "x is not y" is what everybody else uses, which makes it the clear winner. It doesn't matter that it "looks more like English" or not; everyone uses it, which means every user of Python--even Chinese users, whose language Python looks nothing like--will understand it at a glance, where the slightly less common syntax will take a couple extra brain cycles to parse.
Don't be different just for the sake of being different, at least in this field.
Personally, I use
which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.
TLDR: The bytecode compiler parses them both to
x is not None
- so for readability's sake, useif x is not None
.Readability
We use Python because we value things like human readability, useability, and correctness of various paradigms of programming over performance.
Python optimizes for readability, especially in this context.
Parsing and Compiling the Bytecode
The
not
binds more weakly thanis
, so there is no logical difference here. See the documentation:The
is not
is specifically provided for in the Python grammar as a readability improvement for the language:And so it is a unitary element of the grammar as well.
Of course, it is not parsed the same:
But then the byte compiler will actually translate the
not ... is
tois not
:So for the sake of readability and using the language as it was intended, please use
is not
.To not use it is not wise.
if not x is None
is more similar to other programming languages, butif x is not None
definitely sounds more clear (and is more grammatically correct in English) to me.That said it seems like it's more of a preference thing to me.
I would prefer the more readable form
x is not y
than I would think how to eventually write the code handling precedence of the operators in order to produce much more readable code.