看下面的代码:
import asyncio
async def count():
print("One")
await asyncio.sleep(1)
print("Two")
async def main():
await asyncio.gather(count(), count(), count()) # THIS LINE
if __name__ == "__main__":
import time
s = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - s
print(f"{__file__} executed in {elapsed:0.2f} seconds.")
看
# THIS LINE
,asyncio.gather 可以在其参数 count() 返回值之前完成其功能。
但是作为我对Python的理解。 python解释器将外部函数视为黑匣子,并首先重点评估其参数。当其参数的所有值完成后,解释器会将其传递给函数来执行。
根据我上面的理解,不会有什么区别:
await asyncio.gather(count(), count(), count())
和
await (count(), count(), count())
后一个是一个未赋值的元组。
但是
asyncio.gather
如何以这样的形式来落实其工作呢?
因为函数
count
被定义为async def count():
,所以当调用它时 - 它不是执行函数,而是返回一个协程对象。
协程(例如
count
)仅在使用 await
时才开始执行。
表达式await count()
的求值方式如下:
await
开始等待协程。None
(因为函数 count
不返回任何内容)await count()
返回 None
。所以,对于你的例子 - 执行时
await asyncio.gather(count(), count(), count())
:
count
被调用 3 次,返回 3 个不同的协程。asyncio.gather
。asyncio.gather
本身返回一个协程。await
正在等待 asyncio.gather
,后者等待其所有参数协程。第二个表达式
await (count(), count(), count())
不起作用,因为你不能在不是协程的东西上使用 await
。