有没有理由在python asyncio中`return await ...`? [英] Is there ever a reason to `return await ...` in python asyncio?

查看:85
本文介绍了有没有理由在python asyncio中`return await ...`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在js中,它不会在 return 语句(即 Return await ... )之前添加任何内容来执行 await ,但是在python中也是如此,或者这以某种方式使实现的可能性更高或有所不同?

I know in js it doesn't add anything to do an await before a return statement (i.e. return await ...), but is it the case in python too, or this somehow makes the materialization more probable or different?

如果两者不相等,那么最佳实践是什么?

If the two are not equivalent, what is the best practice?

推荐答案

给出:

async def foo() -> str:
    return 'bar'

调用 foo 时得到的是

What you get when calling foo is an Awaitable, which obviously you'd want to await. What you need to think about is the return value of your function. You can for example do this:

def bar() -> Awaitable[str]:
    return foo()  # foo as defined above

那里, bar 是一个同步函数,但返回一个 Awaitable ,该结果会生成一个 str .

There, bar is a synchronous function but returns an Awaitable which results in a str.

async def bar() -> str:
    return await foo()

以上, bar 本身是 async ,并且在被调用时会产生 Awaitable ,这会导致产生 str ,与上述相同.这两种用法之间没有真正的区别.差异出现在这里:

Above, bar itself is async and results in an Awaitable when called which results in a str, same as above. There's no real difference between these two usages. Differences appear here:

async def bar() -> Awaitable[str]:
    return foo()

在该示例中,调用 bar 会导致 Awaitable ,这会导致 Awaitable ,这会导致 str ;很不一样.如果您天真地使用上面的方法,则会得到以下结果:

In that example, calling bar results in an Awaitable which results in an Awaitable which results in a str; quite different. If you naïvely use the above, you'll get this kind of result:

>>> asyncio.run(bar())
<coroutine object foo at 0x108706290>
RuntimeWarning: coroutine 'foo' was never awaited

根据经验,每次对 async 的调用都必须在某个地方进行 await 一次.如果您有两个 async ( async def foo async def bar ),但在 bar中没有任何 await ,那么 bar 的调用方必须 await 两次,这很奇怪.

As a rule of thumb, every call to an async must be awaited somewhere once. If you have two async (async def foo and async def bar) but no await in bar, then the caller of bar must await twice, which would be odd.

这篇关于有没有理由在python asyncio中`return await ...`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆