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 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...
It seems like the only way is to write my own DFS walk function, is does it make sense?
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 owngeneric_visit
.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.Fantastic, it works and it's really simple
So it's the same as a normal NodeVisitor, but I have a defaultdict where I add the type of the node for each son. Then I pass this dictionary to pygraphviz.AGraph and I get my nice result.
The only problem is that the type doesn't say much, but on the other hand using ast.dump() is way too verbose.
Best thing would be to get the actual source code for each node, is that possible?
EDIT: now it's much better, I pass in the constructor also the source code and I try to get the code line if possible, otherwise just print out the type.