all Python 3astterm
ast.Module
root and base nodes
The root node ast.parse returns in the default 'exec' mode: a whole file or code fragment as a list of statements.
Syntax
ast.Module(body, type_ignores)
body holds statements only: even a lone expression '1 + 2' arrives wrapped in an Expr, with the value in body[0].value. A Module built by hand needs type_ignores=[] on Python 3.11 and earlier, otherwise compile() fails with 'required field type_ignores missing'. Call ast.fix_missing_locations before compile() too: hand-made nodes have no lineno.
Examples
import ast
tree = ast.parse('x = 1\nprint(x)')
print(type(tree).__name__) # → Module
print([type(s).__name__ for s in tree.body]) # → ['Assign', 'Expr']
print(type(ast.parse('1 + 2').body[0].value).__name__) # → BinOp
import ast
call = ast.Expr(ast.Call(ast.Name('print', ast.Load()), [ast.Constant(42)], []))
tree = ast.fix_missing_locations(ast.Module(body=[call], type_ignores=[]))
exec(compile(tree, '<ast>', 'exec'))
# → 42
See also
Open in the full glossarydocs.python.orgReport an inaccuracy