我们如何调用需要协程的普通函数? [英] 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
如果 bar
是一个协程,这可以正常工作.如果 bar
是一个普通函数,我需要做什么(即我需要做什么来包装对 bar
的调用),以便此代码执行正确的操作?
This works fine if bar
is a coroutine.
What do I need to do (i.e. 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?
使用 async def
定义协程是完全可能的,即使它从不做任何异步操作(即从不使用 await
).但是,问题询问如何在 foo
的代码中包装/修改/调用常规函数 bar
,以便可以等待 bar
.
It is perfectly possible to define a coroutine with async def
even if it never does anything asynchronous (i.e. never uses 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.
推荐答案
只需使用 asyncio.coroutine 如果需要:
Simply wrap your synchronous function with asyncio.coroutine if needed:
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)()
这篇关于我们如何调用需要协程的普通函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!