python:迭代列表或异步生成器

2024-04-27 01:10:53 发布

您现在位置:Python中文网/ 问答频道 /正文

由于python中引入了迭代器,所以始终可以不关心您是在处理迭代器还是在处理列表:

from random import random

def gen_list():
    print('gen')
    for i in range(10):
        yield i

def return_list():
    print('return')
    return [i for i in range(10)]


if random() > 0.5:
    x = gen_list()
else:
    x = return_list()

for i in x:
    pass

pep492引入了asynchronous iteratorsasync for语法。我看不到为异步迭代器的使用者添加语法这一新负担的任何理由

在我的代码中,我有时处理列表(来自缓存),有时处理异步生成器:

import asyncio
from random import random

def is_small_and_in_cache():
    if random() > 0.5:
        print('in fake cache')
        return [i for i in range(10)]

async def get_progressively():
    print('gen')
    for i in range(10):
        # e.g. an await here
        await asyncio.sleep(0.1)
        yield i

async def main():
    x = is_small_and_in_cache()
    if x is None:
        x = get_progressively()

    async for i in x:
        pass

asyncio.run(main())

但上述方法在TypeError: 'async for' requires an object with __aiter__ method, got list时失败(一半时间)

主要问题:如何写这篇文章,以便我们可以处理这两个问题?我应该尝试将列表转换为虚拟异步生成器,还是包装异步生成器以便它生成列表

侧任务:是否有任何建议来摆脱(对我来说显然是非音速的)async for构造,即为什么常规for循环不能处理异步生成器?Python3x是否在可用性方面迷失了方向


Tags: inimportasyncio列表forasyncreturnif
1条回答
网友
1楼 · 发布于 2024-04-27 01:10:53

语法的存在是为了警告您,您的“循环”实际上可能包括挂起整个调用,允许其他代码运行,以便您知道在每次迭代的顶部都有处于一致状态的适当数据。它哪儿也去不了

当然,协同程序没有要挂起的,您可以使用它使包装任何可重用的琐事:

async def desync(it):
  for x in it: yield x

这通常比仍然异步的相反数字更有用,因为它必须聚集到列表中:

async def gather(ai):
  ret=[]
  async for x in ai: ret.append(x)
  return ret

因为它允许在完全异步的情况下进行适当的交织

相关问题 更多 >