Dan*_*ank 10 python concurrency python-asyncio
考虑一个调用另一个协程的协程:
async def foo(bar):
result = await bar()
return result
Run Code Online (Sandbox Code Playgroud)
如果bar是协程,这可以正常工作.我需要做什么(即我需要将调用包装起来bar),以便这个代码在bar正常函数中做正确的事情?
async def即使它从不做任何异步(即从不使用await),也完全有可能定义一个协同程序.但是,问题是如何bar在代码中包装/修改/调用常规函数foo,bar以便等待.
如果需要,只需使用asyncio.coroutine包装同步函数:
if not asyncio.iscoroutinefunction(bar):
bar = asyncio.coroutine(bar)
Run Code Online (Sandbox Code Playgroud)
由于重新包装协程是安全的,因此实际上不需要协程功能测试:
async_bar = asyncio.coroutine(sync_or_async_bar)
Run Code Online (Sandbox Code Playgroud)
因此,您的代码可以重写如下:
async def foo(bar):
return await asyncio.coroutine(bar)()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3780 次 |
| 最近记录: |