ana*_*chy 4 python syntax asynchronous argument-unpacking python-asyncio
我知道星号用于解包系统参数等值或将列表解包到变量中。
但我之前在这个 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}")
Run Code Online (Sandbox Code Playgroud)
右下方有一个星号async def main function。makerandom有人可以解释它在这种情况下的作用吗?我想了解异步/等待是如何工作的。
我查看了这个答案,Python asterisk before function但它并没有真正解释它。
星号不在之前makerandom,而是在生成器表达式之前
(makerandom(i, 10 - i - 1) for i in range(3))
Run Code Online (Sandbox Code Playgroud)
asyncio.gather不将可迭代作为其第一个参数;它接受可变数量的可等待项作为位置参数。为了从生成器表达式中获取生成器表达式,您需要解压缩生成器。
在这个特殊的例子中,星号解压
asyncio.gather(*(makerandom(i, 10 - i - 1) for i in range(3)))
Run Code Online (Sandbox Code Playgroud)
进入
asyncio.gather(makerandom(0, 9), makerandom(1, 8), makerandom(2, 7))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1532 次 |
| 最近记录: |