all Python 3astterm
ast.Expression
root and base nodes
The root of the tree built by ast.parse(src, mode='eval'): a single expression in the body field, ready to be compiled for eval().
Syntax
ast.parse(source, mode='eval') -> ast.Expression(body)
Unlike Module, the body of an Expression is a single node, not a list: tree.body[0] fails with TypeError here. The 'eval' mode rejects statements outright: the string 'x = 1' raises SyntaxError while parsing. Do not confuse it with ast.Expr, the expression statement inside Module.body (such as a bare print(...) call). An Expression tree must be compiled with mode='eval', otherwise compile() raises TypeError.
Examples
import ast
tree = ast.parse('2 * 21', mode='eval')
print(type(tree).__name__, type(tree.body).__name__) # → Expression BinOp
print(eval(compile(tree, '<expr>', 'eval'))) # → 42
import ast
try:
ast.parse('x = 1', mode='eval')
except SyntaxError:
print('mode=eval: only expressions') # → mode=eval: only expressions
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy