在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”的错误。建议解决方案是实现您自己的生成器:
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"对象不是迭代器
我认为,如果你将某个东西称为迭代器,那么它必须具有完全相同的接口,因此我可以编写异步迭代器并在一个大量依赖于next()调用的框架上使用。
如果您需要重写整个代码才能使用异步功能,则任何新的Python功能都是无意义的。
我错过了什么吗?
谢谢!
async_generator
不是迭代器呢? - fenceop''.join([x async for x in xs])
而不能使用''.join(x async for x in xs)
?这只是[]
对异步生成器有特殊的语法吗? - Thomas Ahle[x async for x in xs]
。而(x for x in xs)
是生成器表达式(将另外一对括号简单省略后,可将其作为函数参数传递)。我认为您无法使用异步代码创建生成器对象。因此,(x async for x in xs)
是无效语法。 - Michael Ihnatenkoaiter()
和anext()
,无需调用__aiter__
或__anext__
。https://docs.python.org/3/library/functions.html#anext - Philip Couling