ast.walk
- Python course
- Expert
- Lesson 14/47
- 5 min
Learn to traverse the tree with ast.walk.
What is ast.walk?
ast.walk(tree) is a generator that yields every node in an AST in order. Depth or breadth does not matter; if you just want to see every node it is ideal.
For example for node in ast.walk(tree): lets you iterate all nodes and filter a specific type with isinstance(node, ast.Name). This is enough for simple counters and analysis tools. For more controlled traversal you use NodeVisitor; but for a quick scan ast.walk is the shortest path.
Counting node types
Counting nodes of a specific type with ast.walk is a common task. You initialize a counter, check the type with isinstance inside the loop and increment on match.
For example finding how many Name nodes a piece of code has is useful to measure variable usage. Similarly the count of ast.Call shows how often functions are called. These metrics are the foundation of code-quality tools. You report the result with a print.
Practice Count nodes with ast.walk
Import the module with import ast. Build the tree with ast.parse("a = 1\nb = 2\nc = 3"). Walk the tree with ast.walk; count Name nodes with isinstance(node, ast.Name). Initialize a counter and increment on each match. Print the result.
Starter code
# parse the tree and walk the nodes
# count and print the resultSample solution
import ast
tree = ast.parse("a = 1\nb = 2\nc = 3")
count = 0
for node in ast.walk(tree):
if isinstance(node, ast.Name):
count += 1
print(count)Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match ast.walk concepts
| Term | Meaning |
|---|---|
ast.walk |
Walks all nodes |
for node in |
Loop variable |
isinstance |
Type filter |
tree |
Tree root |
2 What does ast.walk return?
import ast
tree = ast.parse("x = 1")
for n in ast.walk(tree):
print(type(n).__name__)- A list
- A generator Correct answer
- A single node
- A dict
Explanation: answer: a generator. ast.walk yields one node at a time.
3 Complete the ast.walk call
for node in ____(tree):
print(type(node).__name__)
for node in ast.walk(tree):
print(type(node).__name__)
Explanation: ast.walk(tree) walks all nodes.