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.