简体   繁体   English

我们如何调用正常的函数来预期协程?

[英]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.

相关问题 如何泛化可能是异步,龙卷风协程或正常的函数调用? - How to generalize a function call which may be async, tornado coroutine, or normal? 在python中,如何使用兼容正常功能和协程功能的装饰器? - In python,how to use decorator compatible with normal function and coroutine function simply? 如何在事件循环中将协程打包为普通函数? - How can I package a coroutine as normal function in event loop? Python从普通函数中调用协程 - Python calling coroutine from normal function 如何修复协同程序预期错误? - How to fix a coroutine was expected error? 在无协程函数中,如何从Tornado TCP的协程函数中获取返回值? - In a no-coroutine function, how do you get a return value from coroutine function of Tornado TCP? 我需要通过我的代码进行解释,我们需要在哪里定义 init 方法并声明“self”。 如何在每种情况下调用 function 在我的代码中给出 - I need an explanation through my code, where do we need to define init method and declare "self". How to call a function in each cases give in my code 不产生协程的程序和正常同步功能之间有什么区别吗? - Is there any difference between a coroutine that doesn't yield and a normal sync function? 在Python协程中更新函数调用 - Update Function Call within Python Coroutine 如何对协程进行评分,并在限制后重新调用协程? - How to rate limit a coroutine and re-call the coroutine after the limit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM