【发布时间】:2014-05-04 00:02:57
【问题描述】:
ast 使用什么类型的树遍历(特别是ast.NodeVisitor())?当我创建一个堆栈并将遍历的每个节点推入堆栈时,结果似乎是“广度优先”树遍历。这意味着顺序取决于树中的级别。
例如。树的样子
Module
Assign
Name
Store
Call
Attribute
Str
Load
堆栈看起来像
[Module,Assign,Name,Call,Store,Attribute,Str,Load]
例如。代码
stack = []
class a(ast.NodeTransformer):
def visit_Num(self,node):
stack.append(node)
...
return node
... #this is all the other visit_*() functions
def visit_Str(self,node):
stack.append(node)
...
return node
if __name__ == "__main__":
with open('some_file.py','r') as pt:
tree = ast.parse(pt)
new_tree = a()
new_tree_edit = ast.fix_missing_locations(new_tree.visit(tree)) # I have tried with and without calling fix_missing_locations and got the same results.
print stack
【问题讨论】:
-
您是指
ast.walk()函数,还是ast.NodeVisitor()? -
@Martijn Pieters - 我的意思是 ast.NodeVisitor(),但你知道 ast.walk() 方法是否使用不同的遍历吗?
标签: python stack abstract-syntax-tree tree-traversal