all Python 3astfunction
ast.walk()
helper functions
A generator that yields every node of a tree, including the root itself. The shortest way to find all calls, names or loops in some code.
Syntax
for node in ast.walk(tree): ...
The order is breadth-first, not source order: nodes of a nested expression can come before neighbouring lines, so sort by (lineno, col_offset) when order matters. walk knows no context (which function a node is in) and also yields helper nodes such as Load and Add; when you need context or node replacement, use NodeVisitor/NodeTransformer.
Examples
import ast
tree = ast.parse('print(len(s))\nx = input()')
calls = [n.func.id for n in ast.walk(tree) if isinstance(n, ast.Call)]
print(sorted(calls)) # → ['input', 'len', 'print']
import ast
tree = ast.parse('a + f(b)', mode='eval')
print([type(n).__name__ for n in ast.walk(tree)][:5])
# → ['Expression', 'BinOp', 'Name', 'Add', 'Call']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy