Python AST 处理
我有一个 Python AST [由 ast.parse() 返回]。
我知道这是类方法的 AST。
如何找到对同一类的其他方法的所有调用?
基本上,我想收集类似的内容:
['foo', 'bar']
对于这样的代码片段:
def baz(self): # this is a class method
'''baz docstring'''
self.foo() + self.bar()
我需要一个函数,该函数将接受 AST 并返回在该方法的方法中调用的类的其他方法[字符串形式的方法名称]的列表同一个班级。
I have a Python AST [as returned by ast.parse()].
I know this is an AST of a class method.
How do I find all calls to other methods of the same class?
Basically, I want to collect something like:
['foo', 'bar']
for a code snippet like:
def baz(self): # this is a class method
'''baz docstring'''
self.foo() + self.bar()
I need a function that will accept an AST and will return the list of other methods [method names as strings] of the class that are being invoked inside a method of the same class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般方法是子类
ast.NodeVisitor
:但是,这只会捕获对
self.something
的“立即”调用。在一般情况下,您可以使用例如somelist.append(self.blah)
,然后在代码中稍后使用somelist[i + j]()
:确定的问题无论后者是对 self.blah 的调用,还是对其他与当前实例的方法无关的可调用函数的调用,都是图灵完备的(CS 术语“在一般情况下完全无法解决”)就像数学家可能会说“NP-hard”一样;-)。但如果您需要的只是解决简单的“立即呼叫”案例,那么您就可以开始了;-)。
The general approach is to subclass
ast.NodeVisitor
:However, this will only catch "immediate" calls to
self.something
. In the general case you could have e.g.somelist.append(self.blah)
and then much later in the codesomelist[i + j]()
: the problem of determining whether the latter is a call toself.blah
or to some other callable that has nothing to do with methods of the current instance is Turing-complete (CS jargon for "completely insoluble in the general case", much like a mathematician might say "NP-hard";-).But if all you need is to solve the simple "immediate call" case, you're good to go;-).