On this page
ast.walk
Prev: ast.unparse | Up: ast
Rel: ast.Add, ast.alias, ast.And, ast.AnnAssign
Ref: docs.python.org — ast.walk
Tags: #public #python3 #stdlib #ast
Import
import ast
from ast import walk
Signature & Overview
ast.walk(node)
Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
Usage
import ast
tree = ast.parse("def f(x): return x + 1")
names = [n.id for n in ast.walk(tree) if isinstance(n, ast.Name)]
assert names == ["x"]
Gotchas
- Breadth-first, no parent pointers: Use
ast.NodeVisitorif you need ordered depth-first traversal or scope tracking.
REPL Inspect
from ast import walk
help(walk)
Linked from
Related notes
- tuts/python3/stdlib_module/ast/unparse Linked here; links to this page; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/Add Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/alias Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/And Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/AnnAssign Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/AST Linked here; shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ast/arg shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/arguments shared tags: #ast, #stdlib
- tuts/python3/stdlib_module/ast/Assert shared tags: #ast, #stdlib