Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example using google codesearch or plain google.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
generic_visit
is called when a custom visitor (ie visit_Name) can't be found. Here's a piece of code I wrote recently with ast.NodeVisitor: https://bitbucket.org/pypy/pypy/src/6df19fd2b6df6058daf162100cf7ee4521de5259/py/_code/_assertionnew.py?at=default&fileviewer=file-view-default It interprets the AST nodes to gain debugging information about some of them and falls back in withgeneric_visit
when a special implementation isn't provided.ast.visit
-- unless you override it in a subclass, of course -- when called to visit anast.Node
of classfoo
, callsself.visit_foo
if that method exists, otherwiseself.generic_visit
. The latter, again in its implementation in classast
itself, just callsself.visit
on every child node (and performs no other action).So, consider, for example:
Here, we're overriding
generic_visit
to print the class name, but also calling up to the base class (so that all children will also be visited). So for example...:emits:
But suppose we didn't care for Load nodes (and children thereof -- if they had any;-). Then a simple way to deal with that might be, e.g.:
Now when we're visiting a Load node,
visit
dispatches, NOT togeneric_visit
any more, but to our newvisit_Load
... which doesn't do anything at all. So:or, suppose we also wanted to see the actual names for Name nodes; then...:
But, NodeVisitor is a class because this lets it store information during a visit. Suppose all we want is the set of names in a "module". Then we don't need to override
generic_visit
any more, but rather...:This kind of thing is a more typical use case than ones requiring overrides of
generic_visit
-- normally, you're only interested in a few kinds of nodes, like we are here in Module and Name, so we can just overridevisit_Module
andvisit_Name
and let ast'svisit
do the dispatching on our behalf.Looking at the code in ast.py it's not that hard to copy paste and roll your own walker. E.g.
Prints out