可等待的 iter() 替代品?

jup*_*bjy 5 python python-asyncio

通常在 IO 操作中我们用来iter()读取哨兵值:

from sys import stdout

with open(r"Z:\github\StackOverFlow\temp.json", "r") as fp:
    for chunk in iter(lambda :fp.read(64), ""):
        stdout.write(chunk)
Run Code Online (Sandbox Code Playgroud)

iter()但是除了for waitable之外还有其他选择吗asyncio.Queue.get()

from sys import stdout

with open(r"Z:\github\StackOverFlow\temp.json", "r") as fp:
    for chunk in iter(lambda :fp.read(64), ""):
        stdout.write(chunk)
Run Code Online (Sandbox Code Playgroud)

当然,这不会起作用,因为它需要可调用,await不能在非异步函数内调用。

情况不允许queue.get_nowait(),因为队列大部分时间都是空的。


简单的修复方法是使用while循环:

for val in iter(lambda: await queue.get(), sentinel):
    queue.task_done()
    print(val)
Run Code Online (Sandbox Code Playgroud)

但我担心这是否会损害可读性和清晰度。

Sha*_*ger 5

您可以改进循环中使用的内容,while将海象集成到while条件中:

while (val := await queue.get()) is not None:
    queue.task_done()
    print(val)
Run Code Online (Sandbox Code Playgroud)

这可以让您获得所需结果的同等简洁性,并且相对于您所需的两个参数iter解决方案来说并不是特别难看(两个参数iter首先是一个相对难看的东西)。