定义Python异步函数时,会发生什么以及它是如何工作的?

问题描述 投票:0回答:1

看下面的代码:

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
如何以这样的形式来落实其工作呢?

或者异步函数定义本身有什么特殊之处?

python python-3.x function parameters async-await
1个回答
1
投票

因为函数

count
被定义为
async def count():
,所以当调用它时 - 它不是执行函数,而是返回一个协程对象。

协程(例如

count
)仅在使用
await
时才开始执行。 表达式
await count()
的求值方式如下:

  1. 调用 count,返回一个协程。
  2. await
    开始等待协程。
  3. 协程执行,返回
    None
    (因为函数
    count
    不返回任何内容)
  4. 表达式
    await count()
    返回
    None

所以,对于你的例子 - 执行时

await asyncio.gather(count(), count(), count())
:

  1. count
    被调用 3 次,返回 3 个不同的协程。
  2. 这些协程作为参数传递给
    asyncio.gather
  3. asyncio.gather
    本身返回一个协程。
  4. await
    正在等待
    asyncio.gather
    ,后者等待其所有参数协程。

第二个表达式

await (count(), count(), count())
不起作用,因为你不能在不是协程的东西上使用
await

© www.soinside.com 2019 - 2024. All rights reserved.