在Python中,如何找到(1)调用特定函数和(2)具有某个装饰器的函数?

时间:2015-06-18 02:58:19

标签: python

例如,如果您有一个文件code.py

def functionA():
    # does something

@some_decorator
def functionB():
    functionA()

@some_decorator
def functionC():
    functionD()

def functionD():
    functionA()

如何编写函数find_callers_with_decorator,以便在致电find_callers_with_decorator(code.py, 'some_decorator')时,它会返回['functionB', 'functionC']

1 个答案:

答案 0 :(得分:1)

您可以使用ast模块:

import ast

def find_callers_with_decorator(filename, decorator):
    with open(filename, 'rb') as handle:
        module = ast.parse(handle.read())

    for node in module.body:
        if not isinstance(node, ast.FunctionDef):
            continue

        if decorator in (d.id for d in node.decorator_list):
            yield node.name