【发布时间】:2021-10-01 02:36:49
【问题描述】:
我知道星号用于解压缩系统参数等值或将列表解压缩为变量。
但我之前在这个 asyncio 示例中没有见过这种语法。
我在这里阅读了这篇文章,https://realpython.com/async-io-python/#the-10000-foot-view-of-async-io,但我不明白星号运算符在这种情况下在做什么。
#!/usr/bin/env python3
# rand.py
import asyncio
import random
# ANSI colors
c = (
"\033[0m", # End of color
"\033[36m", # Cyan
"\033[91m", # Red
"\033[35m", # Magenta
)
async def makerandom(idx: int, threshold: int = 6) -> int:
print(c[idx + 1] + f"Initiated makerandom({idx}).")
i = random.randint(0, 10)
while i <= threshold:
print(c[idx + 1] + f"makerandom({idx}) == {i} too low; retrying.")
await asyncio.sleep(idx + 1)
i = random.randint(0, 10)
print(c[idx + 1] + f"---> Finished: makerandom({idx}) == {i}" + c[0])
return i
async def main():
res = await asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))
return res
if __name__ == "__main__":
random.seed(444)
r1, r2, r3 = asyncio.run(main())
print()
print(f"r1: {r1}, r2: {r2}, r3: {r3}")
在async def main function 下方makerandom 之前有一个星号。有人可以解释它在这种情况下的作用吗?我正在尝试了解 async / await 的工作原理。
我看了这个答案,Python asterisk before function,但它并没有真正解释它。
【问题讨论】:
-
它的意思和其他地方的意思一样。
标签: python asynchronous syntax python-asyncio argument-unpacking