我正在研究Python 2.6.5。
给定一个抽象语法树,我想获取它的子级。
大多数 StackOverflow 帖子都讨论了ast.NodeVisitor
和其中定义的方法:visit()
、generic_visit()
。但是,visit()
和generic_visit()
不会给孩子,而是直接递归地将函数应用于它们。
有人可以写一个简短的代码来演示它吗?python库中是否存在相同的预定义函数?
包含节点子节点的 attaributes 取决于节点表示的语法类型。 每个节点类还有一个特殊的_fields
属性,该属性列出了该类具有的子节点的属性名称。例如
>>> ast.parse('5+a')
<_ast.Module object at 0x02C1F730>
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02C1FF50>]
>>> ast.parse('5+a').body[0]
<_ast.Expr object at 0x02C1FBF0>
>>> ast.parse('5+a').body[0]._fields
('value',)
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02C1FF90>
>>> ast.parse('5+a').body[0].value._fields
('left', 'op', 'right')
>>> ast.parse('5+a').body[0].value.left
<_ast.Num object at 0x02C1FB70>
等等。
编辑,以澄清正在发生的事情
在继续之前,先看一下CPython抽象语法
考虑:
>>> type(ast.parse('5+a'))
<class '_ast.Module'>
事实上,如果你看一下语法,第一个生产规则是针对模块的。 它似乎采用一系列语句,作为称为 body 的参数。
>>> ast.parse('5+a')._fields
('body',)
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02E965B0>]
AST 的_fields
属性只是"正文",而 body 属性是 AST 节点的序列。 回到语法,查看stmt
的生产规则,我们看到Expr
需要一个名为 value
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02E96330>
如果我们查找 BinOp 的定义,我们会发现它需要 3 个不同的参数,左、操作和右。 我希望你应该能够从那里开始。
ast
模块提供了一个您可能会发现有用的iter_child_nodes
函数。
def iter_child_nodes(node):
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
for name, field in iter_fields(node):
if isinstance(field, AST):
yield field
elif isinstance(field, list):
for item in field:
if isinstance(item, AST):
yield item
`