获取函数或源代码中调用的所有函数

2024-05-16 21:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

最初我认为我必须解析函数的源代码才能得到它调用的所有函数,但即使这样,我也只能得到函数的名称,而不是函数本身

然后我发现了一些与我类似的问题,例如: Find all function calls by a function

尽管所有其他答案都提供了返回函数名列表的解决方案,但它们并不返回实际函数本身。我想得到一个函数中调用的函数列表,或者源代码作为实际函数的列表,这可能吗?我应该使用ast解决方案,但以某种方式将astFunctionDef对象转换为function对象吗?或者这可以通过dis实现吗?以下是我目前掌握的情况:

import dis
def list_func_calls(fn):
    funcs = []
    bytecode = dis.Bytecode(fn)
    instrs = list(reversed([instr for instr in bytecode]))
    for (ix, instr) in enumerate(instrs):
        if instr.opname == "CALL_FUNCTION":
            load_func_instr = instrs[ix + instr.arg + 1]
            funcs.append(load_func_instr.argval)

    return ["%d. %s" % (ix, funcname) for (ix, funcname) in enumerate(reversed(funcs), 1)]

def a():
    print(b())

def b():
    return 'hi'

list_func_calls(a)

我可以想象,从字节码中获取被调用的函数可能会很困难,但我真的不知道,我不太喜欢这个函数,但我想回去:

[<function print>, <function __main__.b()>]

这种事情可能发生吗


Tags: 函数in列表for源代码deffunctionlist