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
`
包含节点子节点的附件取决于节点所表示的语法类型。每个节点类也有一个特殊的
_fields
属性,该属性列出了类所具有的子节点的属性名。例如等等。在
编辑,以澄清发生的事情
在继续之前,请先浏览一下CPython Abstract Grammar
考虑:
^{pr2}$实际上,如果你看一下语法,第一个产生式规则是针对模块的。它似乎需要一系列语句,作为一个名为body的参数。在
AST的
_fields
属性只是“body”,body属性是一系列AST节点。回到语法,在stmt
的产生式规则中,我们看到Expr
使用一个名为value
的表达式如果我们查找BinOp的定义,我们会发现它有3个不同的参数,left、op和right。我希望你能从那里开始。在
ast
模块提供了一个您可能会发现有用的iter_child_nodes
函数。在相关问题 更多 >
编程相关推荐