问题描述
我正在分析python代码生成的AST的乐趣和获利,并且我想拥有比 ast.dump更多的图形化图形,以实际看到所生成的AST。
I'm analyzing the AST generated by python code for "fun and profit", and I would like to have something more graphical than "ast.dump" to actually see the AST generated.
理论上已经是一棵树,因此创建图形应该不太困难,但是我不知道该怎么做。
In theory is already a tree, so it shouldn't be too hard to create a graph, but I don't understand how I could do it.
ast.walk似乎采用了BFS策略,并且visitX方法我看不到父级,或者我似乎没有找到创建图形的方法...
ast.walk seems to walk with a BFS strategy, and the visitX methods I can't really see the parent or I don't seem to find a way to create a graph...
似乎唯一的方法是编写我自己的DFS漫游函数,这有意义吗?
It seems like the only way is to write my own DFS walk function, is does it make sense?
推荐答案
如果您查看ast.NodeVisitor,那是一个相当琐碎的类。您可以将其子类化,也可以根据需要将其步行策略重新实现。例如,以这种方式实现访问节点时保留对父对象的引用非常简单,只需添加一个 visit
方法,该方法也接受父对象作为参数,然后传递该方法。来自您自己的 generic_visit
。
If you look at ast.NodeVisitor, it's a fairly trivial class. You can either subclass it or just reimplement its walking strategy to whatever you need. For instance, keeping references to the parent when nodes are visited is very simple to implement this way, just add a visit
method that also accepts the parent as an argument, and pass that from your own generic_visit
.
PS顺便说一句,看来 NodeVisitor.generic_visit
实现了DFS,所以您要做的就是添加传递的父节点。
P.S. By the way, it appears that NodeVisitor.generic_visit
implements DFS, so all you have to do is add the parent node passing.
这篇关于Python AST点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!