Traversing Nodes with `ast.NodeVisitor`
`ast.NodeVisitor` traverses syntax trees using the Visitor design pattern. Subclassing it and implementing `visit_<NodeType>` methods lets you inspect specific nodes without writing manual traversal recursion 🚶.
import ast
class FunctionLister(ast.NodeVisitor):
def __init__(self):
self.names = []
def visit_FunctionDef(self, node):
self.names.append(node.name)
self.generic_visit(node) # Recurse into nested children
code = "def alpha(): pass\ndef beta():\n def gamma(): pass"
visitor = FunctionLister()
visitor.visit(ast.parse(code))
print(f"Functions: {visitor.names} 🚶")
# 64. Traversing Nodes with `ast.NodeVisitor` `ast.NodeVisitor` traverses syntax trees using the Visitor design pattern. Subclassing it and implementing `visit_<NodeType>` methods lets you inspect specific nodes without writing manual traversal recursion 🚶. ```python import ast class FunctionLister(ast.NodeVisitor): def __init__(self): self.names = [] def visit_FunctionDef(self, node): self.names.append(node.name) self.generic_visit(node) # Recurse into nested children code = "def alpha(): pass\ndef beta():\n def gamma(): pass" visitor = FunctionLister() visitor.visit(ast.parse(code)) print(f"Functions: {visitor.names} 🚶") ``` Linters and security scanners rely on `NodeVisitor` to detect deprecated library imports, dangerous function calls, and suspicious eval expressions before runtime execution 🛡️! --- ### Question Why must you invoke `self.generic_visit(node)` inside custom `visit_<NodeType>` methods? 🧠 - [ ] a. To instruct the visitor to recurse into nested child nodes beneath the current node 🚶 - [ ] b. To signal the garbage collector to free inspected AST nodes from RAM - [ ] c. To automatically compile the visited statement directly to machine bytecode - [ ] d. To reset Python's interpreter recursion limit after parsing deep code trees --- ### Challenge Build an `ast.NodeVisitor` subclass `ConstantCollector` that collects all integer constant values (`node.value` where `isinstance(node.value, int)`). Visit `ast.parse('a = 10; b = 20; c = "hello"')` and print the collected list. 🎯 <details> <summary>Solution</summary> ```python import ast class ConstantCollector(ast.NodeVisitor): def __init__(self): self.ints = [] def visit_Constant(self, node): if isinstance(node.value, int): self.ints.append(node.value) self.generic_visit(node) v = ConstantCollector() v.visit(ast.parse('a = 10; b = 20; c = "hello"')) print(v.ints) ``` </details>