获取python中函数中使用/调用的函数列表

Obi*_*Jha 9 python python-3.x

是否有任何工具/库可以列出在另一个方法/函数中调用的方法/函数列表?

例如:如果该工具或库运行以下方法

def calculate(a: int, b: int, operator: Operator):
    if operator == Operator.add:
        add(a, b)
    elif operator == Operator.subtract
        subtract(a, b)
Run Code Online (Sandbox Code Playgroud)

然后它应该返回

1. add
2. subtract
Run Code Online (Sandbox Code Playgroud)

这个问题是几乎相同的这一个,但它为Java.

这是什么基本相同PyCharm的呢Find Usage.谢谢!

Jon*_*sky 6

这似乎可以完成工作:

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)]
Run Code Online (Sandbox Code Playgroud)

例:

>>> list_func_calls(calculate)
['1. add', '2. subtract']
Run Code Online (Sandbox Code Playgroud)

这里发生的是:

  1. 我们使函数的Bytecode对象
  2. 我们反转指令列表,因为函数名称将跟随函数调用
  3. 我们遍历列表,对于每个CALL_FUNCTION指令,

  4. 我们使用指令arg参数来告诉我们有多少个参数

  5. 我们回首过去,找到加载我们正在调用的函数的指令

  6. 我们将该函数的名称(instr.argval)添加到列表中,然后我们将其反转,枚举并以请求的格式返回

请注意,自Python 3.6起,共有3 CALL_FUNCTION条指令,因此您必须查看文档以扩展此示例以使其在当前python的情况下具有完整功能


Fab*_* N. 5

更新:增加了对Python2.7
Tested 和 Confirmed 使用的兼容性Python2.7Python3.5以及Python3.6


指出这dis一点的功劳归功于 Patrick Haugh ¹
实现(dis输出的解析)是我自己的:


设置:

import dis
import sys
from contextlib import contextmanager

# setup test environment
def a(_,__):
    pass

def b(_,__,___):
    pass

def c(_):
    pass

def g():
    pass 

d = 4

def test(flag):
    e = c

    if flag:
        a(a(b,c), [l for l in g(1, x=2)])
    else:
        b(a, int(flag), c(e))

    d = d + 1


def calculate(a, b, operator):
    if operator == Operator.add:
        add(a, b)
    elif operator == Operator.subtract:
        subtract(a, b)

class Operator(object):
    add = "add"
    subtract = "subtract"
Run Code Online (Sandbox Code Playgroud)

Python 2/3 兼容性:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

@contextmanager # /sf/answers/847827221/
def captureStdOut(output):
    stdout = sys.stdout
    sys.stdout = output
    try:
        yield
    finally:
        sys.stdout = stdout


""" for Python <3.4 """
def get_instructions(func):
    import StringIO

    out = StringIO.StringIO()
    with captureStdOut(out):
        dis.dis(func)

    return [AttrDict({
               'opname': i[16:36].strip(),
               'arg': int(i[37:42].strip() or 0),
               'argval': i[44:-1].strip()
           }) for i in out.getvalue().split("\n")]


if sys.version_info < (3, 4):
    dis.get_instructions = get_instructions
    import __builtin__ as builtin
else:
    import builtins as builtin
Run Code Online (Sandbox Code Playgroud)

代码:

def get_function_calls(func, built_ins=False):
    # the used instructions
    ins = list(dis.get_instructions(func))[::-1]

    # dict for function names (so they are unique)
    names = {}

    # go through call stack
    for i, inst in list(enumerate(ins))[::-1]:
        # find last CALL_FUNCTION
        if inst.opname[:13] == "CALL_FUNCTION":

            # function takes ins[i].arg number of arguments
            ep = i + inst.arg + (2 if inst.opname[13:16] == "_KW" else 1)

            # parse argument list (Python2)
            if inst.arg == 257:
                k = i+1
                while k < len(ins) and ins[k].opname != "BUILD_LIST":
                    k += 1

                ep = k-1

            # LOAD that loaded this function
            entry = ins[ep]

            # ignore list comprehensions / ...
            name = str(entry.argval)
            if "." not in name and entry.opname == "LOAD_GLOBAL" and (built_ins or not hasattr(builtin, name)):
                # save name of this function
                names[name] = True

            # reduce this CALL_FUNCTION and all its paramters to one entry
            ins = ins[:i] + [entry] + ins[ep + 1:]

    return sorted(list(names.keys()))
Run Code Online (Sandbox Code Playgroud)

输出:

> print(get_function_calls(test))
> ['a', 'b', 'c', 'g']

> print(get_function_calls(test, built_ins=True))
> ['a', 'b', 'c', 'g', 'int']

> print(get_function_calls(calculate))
> ['add', 'subtract']
Run Code Online (Sandbox Code Playgroud)

¹由于Patrick Haugh的评论dis超过 2 小时,我认为这是免费的......