gpt4 book ai didi

python AST : How to get the children of a node

转载 作者:太空宇宙 更新时间:2023-11-03 13:52:00 25 4
gpt4 key购买 nike

我正在使用 Python 2.6.5。

给定一个抽象语法树,我想获得它的子树。

大多数 StackOverflow 帖子都讨论了 ast.NodeVisitor 以及其中定义的方法:visit()generic_visit()。但是,visit()generic_visit() 不给 child ,而是直接在他们身上递归地应用函数。

有人可以写一段简短的代码来演示吗?python 库中是否存在相同的预定义函数?

最佳答案

包含节点子节点的属性取决于节点表示的语法类型。每个节点类还有一个特殊的 _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 Abstract Grammar

考虑:

>>> type(ast.parse('5+a'))
<class '_ast.Module'>

其实看语法的话,第一个产生式规则是针对Module的。它似乎采用一系列语句作为称为主体的参数。

>>> ast.parse('5+a')._fields
('body',)
>>> ast.parse('5+a').body
[<_ast.Expr object at 0x02E965B0>]

AST 的_fields 属性就是“body”,body 属性是一系列AST 节点。回到语法,查看 stmt 的产生式规则,我们看到 Expr 接受一个名为 value

的 expr
>>> ast.parse('5+a').body[0].value
<_ast.BinOp object at 0x02E96330>

如果我们查看 BinOp 的定义,我们会发现它有 3 个不同的参数,left、op 和 right。我希望你应该能够从那里继续。

关于 python AST : How to get the children of a node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6009663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com