gpt4 book ai didi

python - 在 Python 中获取 AST 节点的父节点

转载 作者:太空狗 更新时间:2023-10-29 17:42:44 27 4
gpt4 key购买 nike

我正在使用 Python 3 中的抽象语法树。ast 库提供了很多获取节点子节点的方法(您可以使用 iter_child_nodes()walk()) 但没有办法获得一个的parent。此外,每个节点都有指向其子节点的链接,但没有指向其父节点的链接。

如果我不想为 ast 库编写一些插件,如何获取 AST 节点的父节点

最正确的方法是什么?

最佳答案

这是一些实际的代码:

for node in ast.walk(root):
for child in ast.iter_child_nodes(node):
child.parent = node

不需要哈希表,直接在节点上放一个属性即可。

关于python - 在 Python 中获取 AST 节点的父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570992/

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