在Python中,如何找到(1)调用特定函数和(2)具有特定修饰符的函数?
例如,如果您有一个文件在Python中,如何找到(1)调用特定函数和(2)具有特定修饰符的函数?,python,Python,例如,如果您有一个文件code.py: def functionA(): # does something @some_decorator def functionB(): functionA() @some_decorator def functionC(): functionD() def functionD(): functionA() 如何编写函数find_callers\u with_decorator,以便在调用find_callers\u w
code.py
:
def functionA():
# does something
@some_decorator
def functionB():
functionA()
@some_decorator
def functionC():
functionD()
def functionD():
functionA()
如何编写函数
find_callers\u with_decorator
,以便在调用find_callers\u with_decorator(code.py,'some_decorator')
时,它返回['functionB','functionC']
?您可以使用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
@用户1449565:这不是很具体。它适用于您的示例代码。您能提供您的实际代码吗?完全相同的代码并出现错误:
AttributeError:'Attribute'对象没有属性“id”
。我有Python 2.7.2。您能将输出粘贴到这里吗?@user1449565:您的代码没有编译,它有语法错误(您的function
没有正文)。我在函数体中添加了pass
,因此它被编译。我在functinoA
中添加了一个pass,如果您查看我粘贴的错误,您将看到它与d.id
相关。你能粘贴你的输出/python版本吗?@user1449565:python 2.7.9和3.4.3<代码>列表(使用_decorator('code.py','some _decorator')查找_调用者)==['functionB','functionC']。