例如,如果您有一个文件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']
?
答案 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