我们如何在需要协程的地方调用普通函数? [英] 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 $定义协程c $ c>,即使它从不执行任何异步操作(即,从不使用
>这样就可以等待 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屋!