1047

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

General Grievance
5,09939 gold badges39 silver badges58 bronze badges
asked Apr 26, 2010 at 3:10
6
  • 61
    is not is an operator in it's own right. Like !=. If you prefer not x is None then your should also prefer not a == b over a != b. Commented Mar 14, 2018 at 10:12
  • @TomaszGandor I no longer have this opinion about not x is None (the answers here convinced me) - it is, however, worth noting that not a == b is the preferred style in Python, compared to a != b. Commented Mar 14, 2018 at 14:20
  • 16
    @orokusaki is not a == b really the preferred style? I have never seen it done that way and everywhere I look people all use !=. Commented Dec 7, 2018 at 15:56
  • 7
    @orokusaki In Python readability counts so it is a preferred style to use one operator != instead of two operators not, ==. Commented Jan 21, 2019 at 15:54
  • 1
    PEP8 explicitly specifies that the former (if foo is not None) is "correct", while the latter is "wrong". Commented Sep 27, 2023 at 12:34

9 Answers 9

1320

There's no performance difference, as they 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

Stylistically, 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.

answered Apr 26, 2010 at 3:55
Sign up to request clarification or add additional context in comments.

9 Comments

Unless the same human reader thought it was x is (not y). But I tend to agree with you for your other reasoning.
additionally "is not" is less ambiguous in this context "if a is not None and b is None:" vs "if not a is None and b is None:"
the operator should be "aint"
or "unless" (if not x is None -> unless x is None)
I think exactly the opposite is true. The first time I saw x is not y I thought the programmer was comparing x to "not y".
|
443

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

Arsen Khachaturyan
8,4304 gold badges46 silver badges47 bronze badges
answered Apr 26, 2010 at 3:13

Comments

144

Code should be written to be understandable to the programmer first, and the compiler or interpreter second. The "is not" construct resembles English more closely than "not is".

answered Apr 26, 2010 at 3:15

1 Comment

"Code should be written to be understandable to the programmer first": That was the principle used to design COBOL, a language from non academics, which received much condescension from academics, some being legitimate, most not. As for the reasons... "For a computer scientist to write sympathetically about COBOL is an act bordering on heresy. It requires courage because academic colleagues and data processing professionals are both likely to be suspicious of my motives."
48

Python if x is not None or if not x is None?

TLDR: The bytecode compiler parses them both to x is not None - so for readability's sake, use if 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 than is, so there is no logical difference here. See the documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

The is not is specifically provided for in the Python grammar as a readability improvement for the language:

comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'

And so it is a unitary element of the grammar as well.

Of course, it is not parsed the same:

>>> import ast
>>> ast.dump(ast.parse('x is not None').body[0].value)
"Compare(left=Name(id='x', ctx=Load()), ops=[IsNot()], comparators=[Name(id='None', ctx=Load())])"
>>> ast.dump(ast.parse('not x is None').body[0].value)
"UnaryOp(op=Not(), operand=Compare(left=Name(id='x', ctx=Load()), ops=[Is()], comparators=[Name(id='None', ctx=Load())]))"

But then the byte compiler will actually translate the not ... is to is not:

>>> import dis
>>> dis.dis(lambda x, y: x is not y)
 1 0 LOAD_FAST 0 (x)
 3 LOAD_FAST 1 (y)
 6 COMPARE_OP 9 (is not)
 9 RETURN_VALUE
>>> dis.dis(lambda x, y: not x is y)
 1 0 LOAD_FAST 0 (x)
 3 LOAD_FAST 1 (y)
 6 COMPARE_OP 9 (is not)
 9 RETURN_VALUE

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.

answered Jul 20, 2015 at 16:18

1 Comment

"The not binds more weakly than is, so there is no logical difference here" -- except that Python does not have to enforce logical and algebraic identities to hold (no intrinsic reason for (1 + 2)*3 to evaluate the same as 1*3 + 2*3). Here apparently Python is cheating and optimising UNARY_NOT away.
36

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.

answered Apr 26, 2010 at 7:18

Comments

19

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

answered Jun 26, 2016 at 16:14

2 Comments

A fair argument that I agree with, but I believe the argument of following idiomatic style is stronger.
+1 To most non-python programmers if x is not None sounds like if x is (not None) which is most likely a coding error. On the other hand to most python programmers if not (x is None) sounds like you have no experience with the language.
11

The is not operator is preferred over negating the result of is for stylistic reasons. "if x is not None:" reads just like English, but "if not x is None:" requires understanding of the operator precedence and does not read like english.

If there is a performance difference my money is on is not, but this almost certainly isn't the motivation for the decision to prefer that technique. It would obviously be implementation-dependent. Since is isn't overridable, it should be easy to optimise out any distinction anyhow.

answered Apr 26, 2010 at 4:32

Comments

3

if not x is None is more similar to other programming languages, but if 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.

answered Apr 26, 2010 at 3:14

Comments

2

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.

answered Sep 24, 2015 at 7:19

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.