使用 Python ast 模块访问语法树中的节点 [英] Visiting nodes in a syntax tree with Python ast module

查看:25
本文介绍了使用 Python ast 模块访问语法树中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 python ast(抽象语法树).

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

我写了以下内容,它访问了 AST 的所有节点.

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

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

if __name__ == '__main__':

    node = ast.parse("a = 1 + 2")

    print ast.dump(node)

    v = Py2Neko()
    v.visit(node)

然后在 Py2Neko 类中添加了一些方法

Then added some methods to Py2Neko class

def visit_Print(self, node):
    print "Print :"

def visit_Assign(self, node):
    print "Assign :"

def visit_Expr(self, node):
    print "Expr :"

但是,当它遇到打印"语句或赋值或表达式时,它似乎停止了并且不再继续.

But then when it encounters a "print" statement or an assignement or an expression it seems that it stops and isn't going further.

它输出:

Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=Num(n=1), op=Add(),       right=Num(n=2)))])
Module
Assign :

谁能告诉我我做错了什么.

Can someone tell me what I did wrong.

我使用的是 Python 2.6.6

I'm using Python 2.6.6

推荐答案

由于您的visit_Assign方法没有显式处理Assign节点的子节点,语法树的遍历就到此为止.

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

如果您查看 ast.py 实现中的 NodeVisitor.generic_visit 方法,您会看到它遍历当前节点的子节点.因此,您可以从需要处理子项的每个方法中显式调用基类 generic_visit 方法:

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)

这篇关于使用 Python ast 模块访问语法树中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆