all Python 3astterm
ast.BinOp
expressions
A binary operation node: left operand, operator and right operand — a + b, a * b, a | b and the other arithmetic and bitwise operations.
Syntax
ast.BinOp(left, op, right)
Precedence and parentheses are not stored — they become the shape of the tree: 1 + 2 * 3 gives a BinOp whose right is another BinOp with Mult. Comparisons (a < b) are Compare, and and/or are BoolOp, even though they look binary too. The operator sits in op as an instance (Add(), Mult()), so check isinstance(node.op, ast.Add) rather than comparing with '+'.
Examples
import ast
node = ast.parse('1 + 2 * 3', mode='eval').body
print(type(node.op).__name__, type(node.right).__name__) # → Add BinOp
print(type(node.right.op).__name__) # → Mult
import ast
node = ast.parse('(1 + 2) * 3', mode='eval').body
print(type(node.op).__name__, type(node.left).__name__) # → Mult BinOp
print(ast.unparse(node)) # → (1 + 2) * 3
See also
Open in the full glossarydocs.python.orgReport an inaccuracy