调用特定功能的功能列表

时间:2019-02-19 13:31:50

标签: python

如何获取在python程序中调用特定函数的函数列表。

例如,如果代码如下:

def myFunc():
  pass

def a():
  myFunc()

def b():
  myFunc()

然后,调用myFunc的函数将是ab

如果程序中包含大量功能,那是最好的方法。

谢谢。

2 个答案:

答案 0 :(得分:2)

这是一种解析模块源代码并显示引用特定变量的每个函数/方法的名称的方法。

import sys
import inspect
import ast

class NameWatcher(ast.NodeVisitor):
    def __init__(self, target):
        self.target = target
        self.current_path = []
        self.results = []
    def visit_FunctionOrClassDef(self, node):
        self.current_path.append(node.name)
        self.generic_visit(node)
        self.current_path.pop()
    def visit_FunctionDef(self, node): 
        self.visit_FunctionOrClassDef(node)
    def visit_ClassDef(self, node):
        self.visit_FunctionOrClassDef(node)
    def visit_Name(self, node):
        if node.id == self.target:
            self.results.append(".".join(self.current_path))

def get_name_locations(node, name):
    watcher = NameWatcher(name)
    watcher.visit(node)
    return watcher.results

class Dog:
    def bark(self):
        myFunc()

def a():
  myFunc()

def b():
  myFunc()

def myFunc():
  pass

current_module = sys.modules[__name__]
source = inspect.getsource(current_module)
ast_node = ast.parse(source)
print(get_name_locations(ast_node, "myFunc"))

结果:

['Dog.bark', 'a', 'b']

注意事项:

  • 这不适用于没有Python源代码的模块。例如内置的math模块。
  • 这将查找名称的实例,包括从未执行过的实例。例如def c(): if False: myFunc()
  • 这将找到名称的实例,包括未实际调用的实例。例如def d(): return myFunc
  • 这将无法定位在不直接使用myFunc名称的情况下调用myFunc的实例。例如def e(): globals()["myFunc"]()

答案 1 :(得分:0)

通过使用@Chris_Rands的建议,我想到了以下解决方案:

l = []
functions = [obj for name, obj in inspect.getmembers(sys.modules[__name__])
                     if inspect.isfunction(obj)]
for i in functions:
    if "myFunc" in i.__code__.co_names:
        l.append(i.__name__)

l包含ab

@Kevin提供了更好的解决方案。

相关问题