在 Python 中获取 AST 节点的父节点 [英] Getting parent of AST node in Python

查看:27
本文介绍了在 Python 中获取 AST 节点的父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with Abstract Syntax Trees in Python 3. The ast library gives many ways to get children of the node (you can use iter_child_nodes() or walk()) but no ways to get parent of one. Also, every node has links to its children, but it hasn't links to its parent.

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

How I can get the parent of AST node if I don't want to write some plugin to ast library?

最正确的方法是什么?

推荐答案

您可以创建一些将 AST 节点与 AST 节点相关联的哈希表,并(递归地)扫描最顶层的 AST 树以在该哈希表中注册每个节点的父节点.

You might create some hash table associating AST nodes to AST nodes and scan (recursively) your topmost AST tree to register in that hash table the parent of each node.

这篇关于在 Python 中获取 AST 节点的父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆