![](/img/trans.png)
[英]How to generalize a function call which may be async, tornado coroutine, or normal?
[英]How do we call a normal function where a coroutine is expected?
考虑一个调用另一个协程的协程:
async def foo(bar):
result = await bar()
return result
如果bar
是协程,这可以正常工作。 我需要做什么(即我需要将调用包装到bar
),以便如果bar
是正常函数,这段代码会做正确的事情?
使用async def
定义协程是完全可能的,即使它从不执行任何异步操作(即从不使用await
)。 但是,问题是如何在foo
的代码中包装/修改/调用常规函数bar
,以便可以等待bar
。
如果需要,只需使用asyncio.coroutine包装同步函数:
if not asyncio.iscoroutinefunction(bar):
bar = asyncio.coroutine(bar)
由于重新包装协程是安全的,因此实际上不需要协程功能测试:
async_bar = asyncio.coroutine(sync_or_async_bar)
因此,您的代码可以重写如下:
async def foo(bar):
return await asyncio.coroutine(bar)()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.