A fast reimplementation of ast.walk()
Actively maintained. Last release 11 days ago. A safe choice.
pip install fast-walkREADME as published on PyPI with version 0.3.1.
fast-walk
A fast reimplementation of Python's ast.walk, written in Rust.
Installation
pip install fast-walk
Usage
Two public entry points, depending on whether you care about traversal order:
import ast
from fast_walk import walk_dfs, walk_unordered
tree = ast.parse("def f(x): return x + 1")
# Strict depth-first pre-order.
for node in walk_dfs(tree):
...
# Implementation-defined order; same node set, faster.
# ast.walk itself makes no ordering guarantee, so this is a drop-in for most code.
for node in walk_unordered(tree):
...
Which one to use
walk_unordered— default choice. Same set of nodes asast.walkbut with better cache behavior (batched dict-metadata prefetching). Roughly 25% faster thanwalk_dfson real Python source.walk_dfs— pick this only if your code actually depends on depth-first pre-order visitation.ast.walkdoes not document an order, so most callers can safely usewalk_unordered.
Visiting only some node types
walk_frontier(node, kinds) returns the descendants whose exact type is in
kinds, in depth-first pre-order, without descending below a match. That is
the set ast.NodeVisitor.generic_visit hands to visit_<kind> methods, so a
visitor whose only methods are visit_<kind> can descend with:
def generic_visit(self, node):
for child in walk_frontier(node, (ast.Call, ast.Attribute)):
self.visit(child)
walk_frontier_edges returns (node, parent, field, index) tuples instead
(index is -1 for a non-list field), which is what a NodeTransformer
needs to put a replacement back.
Other helpers
walk_of_types(node, kinds, prune=None)— every node of the given exact types, in pre-order, descending into matches but not below aprunetype.walk_frontier_events(node, kinds, bracket)— the frontier walk as pairs, with enter/leave events around types, for a visitor that does work around its generic descent.