all Python 3astterm
ast.Is
operators
The marker for the comparison is in an ast tree: it sits in Compare.ops and has no fields.
Syntax
ast.Is()
Linters hunt for exactly this: 'x is 1' or 'x is "a"' is a Compare with Is and a Constant on the right — an identity test against a literal that Python 3.8+ flags with a SyntaxWarning. 'is not' is a single IsNot operator, not Is under Not. Compare marker nodes by type (isinstance), not with ==: ast nodes have no __eq__, so ast.Is() == ast.Is() is False.
Examples
import ast
src = 'if a is None: pass\nif b is 1: pass'
for node in ast.walk(ast.parse(src)):
if isinstance(node, ast.Compare) and isinstance(node.ops[0], ast.Is):
rhs = node.comparators[0]
if isinstance(rhs, ast.Constant) and rhs.value is not None:
print('literal is at line', node.lineno) # → literal is at line 2
See also
Open in the full glossarydocs.python.orgReport an inaccuracy