【发布时间】:2017-02-24 21:32:11
【问题描述】:
在 Python 中,您可以编写一个可迭代的生成器,例如:
def generate(count):
for x in range(count):
yield x
# as an iterator you can apply the function next() to get the values.
it = generate(10)
r0 = next(it)
r1 = next(it) ...
尝试使用异步迭代器时,您会收到“yield inside async”错误。 建议的解决方案是实现您自己的生成器:
class async_generator:
def __aiter__(self):
return self
async def __anext__(self):
await asyncio.sleep()
return random.randint(0, 10)
# But when you try to get the next element
it = async_generator(10)
r0 = next(it)
您收到错误"async_generator" object is not an iterator
我认为如果你要调用 Iterator 是因为它具有完全相同的接口,所以我可以编写异步迭代器并在严重依赖 next() 调用的框架上使用。 如果您需要重写整个代码才能使用异步,那么任何新的 Python 功能都是毫无意义的。
我错过了什么吗?
谢谢!
【问题讨论】:
标签: python python-asyncio