我想获得当前文件中所有Coroutine的列表(在我的代码示例中是extern_method和extern_method2)。其行为应该和我的例子中的 "extern_method "和 "extern_method2 "一样。method_list = [extern_method, extern_method2]
但我希望它能自动被列出。
我的文件结构是这样的。
@wraps(lambda: extern_method)
@my_decorator
async def extern_method(arg)
return arg + "hello"
@wraps(lambda: extern_method2)
@my_decorator
async def extern_method2(arg)
return arg + 123
class myclass:
(...)
def find_extern_methods():
#here missing code
return method_list
(...)
def do_sth_with_methods():
#do sth. with Methods
我试着使用 ast
模块。
with open(basename(__file__), "rb") as f:
g = ast.parse(f.read(), basename(__file__))
for e in g.body:
if isinstance(e, ast.AsyncFuntionDef):
method_list.append(e)
这可能会找到所有的Coroutines, 但我不能提取任何引用。
我也尝试使用。
method_list = inspect.getmembers(basename(__file__), inspect.iscoroutinefunction))
但这也找不到任何东西。
所以我找到了一种方法来找到当前文件本身的Coroutine。
my_module_coros = inspect.getmembers(modules[__name__]), inspect.iscoroutinefunction)
coro_list = [coro[1] for coro in my_module_coros if (inspect.getmodule(coro[1]) == modules[__name__]) and coro[0] != "main"]
这将返回一个Coroutine的列表,不需要main本身。