Python AST:如何获取节点的子节点
我正在研究Python 2.6.5。
给定一个抽象语法树,我想获取它的子树。
大多数 StackOverflow 帖子讨论 ast.NodeVisitor
及其中定义的方法:visit()
、generic_visit()
。 但是,visit()
和 generic_visit()
不会给出子级,而是直接将函数递归地应用于子级。
有人可以写一段简短的代码来演示它吗? python库中是否存在相同的预定义函数?
I am working on Python 2.6.5.
Given a Abstract Syntax Tree, I want to obtain its children.
Most StackOverflow posts discuss ast.NodeVisitor
and the methods defined in it: visit()
, generic_visit()
.
However, visit()
and generic_visit()
do not give the children, rather they directly apply the function recursively on them.
Can someone please write a short code or so to demonstrate it?
Does there exist a predefined function in python library for the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
包含节点子节点的属性取决于节点表示的语法类型。每个节点类还有一个特殊的
_fields
属性,该属性列出了该类所具有的子节点的属性名称。比如说等等。
编辑,以澄清发生了什么
在继续之前,请浏览一下 CPython 抽象语法
考虑一下:
事实上,如果你看一下语法,第一个产生式规则是针对 Module 的。它似乎采用一系列语句,作为称为主体的参数。
AST 的 _fields 属性就是“body”,body 属性是 AST 节点的序列。回到语法,查看
stmt
的产生式规则,我们看到Expr
采用单个 expr,名为value
如果我们查找对于 BinOp 的定义,我们看到它需要 3 个不同的参数:left、op 和 right。我希望你应该能够从那里继续。
The attaributes containing the node's children depend on the type of syntax the node represents. Every node class also has a special
_fields
attribute, that lists the attribute names for the child nodes that class has. For instance,and so on.
Edit, to clarify what's going on
Before going any further, take a glance at the CPython Abstract Grammar
Consider:
In fact, if you look at the grammar, the first production rule is for Module. It appears to take a sequence of statements, as an argument called body.
The
_fields
attribute of the AST is just "body", and the body attribute is a sequence of AST nodes. Back to the grammar, looking in the production rules forstmt
, we see thatExpr
takes a single expr, namedvalue
If we look up the definition for BinOp, we see that it takes 3 different arguments, left, op and right. You should be able to proceed from there, I hope.
ast
模块提供了一个iter_child_nodes
函数,您可能会觉得有用。The
ast
module provides aniter_child_nodes
function you might find useful.