all Python 3astterm
ast.Sub
operators
The subtraction operator - in the op field of BinOp and AugAssign nodes.
Syntax
ast.Sub()
Sub is only the binary minus: -x parses as UnaryOp(USub). Subtraction is left-associative, so a - b - c is a BinOp with the nested BinOp on the left and just c on the right. The parser reuses one Sub object for every occurrence, so compare with isinstance(node.op, ast.Sub), not node.op == ast.Sub().
Examples
import ast
n = ast.parse('a - b - c', mode='eval').body
print(type(n.op).__name__, type(n.left).__name__, n.right.id) # → Sub BinOp c
print(type(ast.parse('-x', mode='eval').body.op).__name__) # → USub
import ast
a = ast.parse('x - y', mode='eval').body.op
b = ast.parse('p - q', mode='eval').body.op
print(a is b, a == ast.Sub(), isinstance(a, ast.Sub)) # → True False True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy