Visiting nodes in a syntax tree with Python ast module

前端 未结 2 352
遇见更好的自我
遇见更好的自我 2021-02-03 13:20

I\'m playing with python ast (abstract syntax tree).

I wrote the following and it visited all nodes of the AST.

import ast

class Py2Neko(ast.NodeVisito         


        
相关标签:
2条回答
  • 2021-02-03 14:01

    For non-terminal nodes, your visit function has to visit the children. See Simple example of how to use ast.NodeVisitor? for some more information.

    0 讨论(0)
  • 2021-02-03 14:06

    Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.

    If you have a look at the NodeVisitor.generic_visit method in the implementation of ast.py, you'll see that it loops through the children of the current node. So, you can explicitly call the base class generic_visit method from each of your methods that needs to process children:

    import ast
    
    class Py2Neko(ast.NodeVisitor):
        def generic_visit(self, node):
            print type(node).__name__
            ast.NodeVisitor.generic_visit(self, node)
    
        def visit_Name(self, node):
            print 'Name :', node.id
    
        def visit_Num(self, node):
            print 'Num :', node.__dict__['n']
    
        def visit_Str(self, node):
            print "Str :", node.s
    
        def visit_Print(self, node):
            print "Print :"
            ast.NodeVisitor.generic_visit(self, node)
    
        def visit_Assign(self, node):
            print "Assign :"
            ast.NodeVisitor.generic_visit(self, node)
    
        def visit_Expr(self, node):
            print "Expr :"
            ast.NodeVisitor.generic_visit(self, node)
    
    if __name__ == '__main__':
        node = ast.parse("a = 1 + 2")
    
        print ast.dump(node)
    
        v = Py2Neko()
        v.visit(node)
    
    0 讨论(0)
提交回复
热议问题