【发布时间】:2021-06-08 11:17:26
【问题描述】:
自从在 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
PEP 492 引入了 asynchronous iterators 和 async 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。
主要问题:如何写这个以便我们可以处理任何一个?我应该尝试将列表转换为虚拟异步生成器,还是包装异步生成器以生成列表?
支线任务:是否有任何建议可以摆脱(对我来说显然是非pythonic)async for 构造,即为什么常规的for 循环不能处理异步生成器? Python3x 在可用性方面已经失去了方向??
【问题讨论】:
标签: python asynchronous python-asyncio