开发者社区> 问答> 正文

在像这样评估其参数之前,Python函数如何生效?

看下面的代码:

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如何以这种形式实现其工作呢?

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 21:51:18 441 0
1 条回答
写回答
取消 提交回答
  • 因为函数count被定义为async def count():,所以在调用它时-不执行该函数,而是返回一个协程对象。

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

    1. count is called, returning a coroutine.
    2. ` await ` starts waiting on the coroutine.
    3. the coroutine executes, returning ` None ` (because the function ` count ` returns nothing)
    4. the expression ` await count() ` returns ` None ` .

    因此,以您的示例为例-执行await asyncio.gather(count(),count(),count())时:

    1. ` count ` is called three times, returning 3 different coroutines.
    2. These coroutines are passed as parameters to ` asyncio.gather ` .
    3. ` asyncio.gather ` itself returns a coroutine.
    4. ` await ` is waiting on ` asyncio.gather ` , which awaits on all its parameter coroutines.

    第二个表达式await(count(),count(),count())不起作用,因为您不能在不是协程的东西上使用await

    回答来源:stackoverflow

    2020-03-24 21:51:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载