NodeVisitor 深度优先遍历 AST,并且在进入时只访问每个节点一次。因此,用它做一些严肃的事情是有问题的。是否可以更改其默认行为?
问问题
2780 次
2 回答
11
也许有人会对一些草拟的例子感兴趣,如何做 DSblizzard 提出的,所以听听我的例子:
import ast
class RecursiveVisitor(ast.NodeVisitor):
""" example recursive visitor """
def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self,node):
func(self,node)
for child in ast.iter_child_nodes(node):
self.visit(child)
return wrapper
@recursive
def visit_Assign(self,node):
""" visit a Assign node and visits it recursively"""
print(type(node).__name__)
@recursive
def visit_BinOp(self, node):
""" visit a BinOp node and visits it recursively"""
print(type(node).__name__)
@recursive
def visit_Call(self,node):
""" visit a Call node and visits it recursively"""
print(type(node).__name__)
@recursive
def visit_Lambda(self,node):
""" visit a Function node """
print(type(node).__name__)
@recursive
def visit_FunctionDef(self,node):
""" visit a Function node and visits it recursively"""
print(type(node).__name__)
@recursive
def visit_Module(self,node):
""" visit a Module node and the visits recursively"""
pass
def generic_visit(self,node):
pass
class SimpleVisitor(ast.NodeVisitor):
""" simple visitor for comparison """
def recursive(func):
""" decorator to make visitor work recursive """
def wrapper(self,node):
func(self,node)
for child in ast.iter_child_nodes(node):
self.visit(child)
return wrapper
def visit_Assign(self,node):
""" visit a Assign node """
print(type(node).__name__)
def visit_BinOp(self, node):
""" visit a BinOp node """
print(type(node).__name__)
def visit_Call(self,node):
""" visit a Call node """
print(type(node).__name__)
def visit_Lambda(self,node):
""" visit a Function node """
print(type(node).__name__)
def visit_FunctionDef(self,node):
""" visit a Function node """
print(type(node).__name__)
@recursive
def visit_Module(self,node):
""" visit a Module node and the visits recursively, otherwise you
wouldn't see anything here"""
pass
def generic_visit(self,node):
pass
# usage example
a = """
b= lambda x: x*5 +5
def hhh(u):
b=19
return u*b
m=hhh(9*4+5)
"""
recursive_visitor = RecursiveVisitor()
simple_visitor = SimpleVisitor()
tree = ast.parse(a)
print('\nvisit recursive\n')
recursive_visitor.visit(tree)
print('\nvisit simple\n')
simple_visitor.visit(tree)
希望有人会发现它有用。
于 2013-02-02T11:18:39.287 回答
3
没有。你应该写你自己的访客。递归地访问所有节点是相当简单的,所以如果 ast 模块的东西不适合你(并且模块中没有任何东西可以做你想做的事,在这种情况下),你自己做也不错.
于 2011-04-04T06:48:53.863 回答