[英]How do we call a normal function where a coroutine is expected?
Consider a coroutine which calls into another coroutine: 考虑一个调用另一个协程的协程:
async def foo(bar):
result = await bar()
return result
This works fine if bar
is a coroutine. 如果bar
是协程,这可以正常工作。 What do I need to do (ie with what do I need to wrap the call to bar
) so that this code does the right thing if bar
is a normal function? 我需要做什么(即我需要将调用包装到bar
),以便如果bar
是正常函数,这段代码会做正确的事情?
It is perfectly possible to define a coroutine with async def
even if it never does anything asynchronous (ie never uses await
). 使用async def
定义协程是完全可能的,即使它从不执行任何异步操作(即从不使用await
)。 However, the question asks how to wrap/modify/call a regular function bar
inside the code for foo
such that bar
can be awaited. 但是,问题是如何在foo
的代码中包装/修改/调用常规函数bar
,以便可以等待bar
。
Simply wrap your synchronous function with asyncio.coroutine if needed: 如果需要,只需使用asyncio.coroutine包装同步函数:
if not asyncio.iscoroutinefunction(bar):
bar = asyncio.coroutine(bar)
Since it is safe to re-wrap a coroutine, the coroutine function test is actually not required: 由于重新包装协程是安全的,因此实际上不需要协程功能测试:
async_bar = asyncio.coroutine(sync_or_async_bar)
Therefore, your code can be re-written as follows: 因此,您的代码可以重写如下:
async def foo(bar):
return await asyncio.coroutine(bar)()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.