有没有理由在python asyncio中`return await ...`? [英] Is there ever a reason to `return await ...` in python asyncio?
问题描述
我知道在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'
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 await
ed 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屋!