all Python 3astterm
ast.NodeVisitor
helper functions
Base class for walking a tree: visit(node) calls the visit_<ClassName> method, or generic_visit when there is none.
Syntax
class V(ast.NodeVisitor):
def visit_Name(self, node): ...
V().visit(tree)
The main trap: once you define visit_FunctionDef, that function's children are no longer visited, so nested functions and calls inside vanish until you call self.generic_visit(node) yourself. A value returned by visit_* comes back only from the top-level visit; generic_visit discards it. To replace nodes use NodeTransformer, and visit_Num and visit_Str are no longer called in 3.14, so use visit_Constant.
Examples
import ast
class Funcs(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_FunctionDef(self, node):
self.names.append(node.name)
src = 'def outer():\n def inner(): pass'
v = Funcs()
v.visit(ast.parse(src))
print(v.names) # → ['outer'] — inner потерян
import ast
class Funcs(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_FunctionDef(self, node):
self.names.append(node.name)
self.generic_visit(node)
v = Funcs()
v.visit(ast.parse('def outer():\n def inner(): pass'))
print(v.names) # → ['outer', 'inner']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy