Reputation: 167
I want to get a list of all Coroutines in the current file (extern_method and extern_method2 in my code example). The behaviour shall be the same like: method_list = [extern_method, extern_method2]
, but I want it to be listed automaticly.
I have a file structure like this:
@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
I tried to use the ast
Module:
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)
This may find all Coroutines, but I can't extract any reference to it.
I also tried to use,
method_list = inspect.getmembers(basename(__file__), inspect.iscoroutinefunction))
but this will not find anything either.
Upvotes: 1
Views: 300
Reputation: 167
So I found a way to find the Coroutines of the current file itself:
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"]
This will return a list of Coroutines, without main itself.
Upvotes: 1