相关疑难解决方法(0)

异步生成器不是迭代器?

在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) ...
Run Code Online (Sandbox Code Playgroud)

尝试使用异步迭代器时,会出现'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)
Run Code Online (Sandbox Code Playgroud)

你得到错误"'async_generator'对象不是迭代器"

我认为如果你打算把它称为迭代器,因为它具有完全相同的接口,所以我可以编写异步迭代器并在依赖于next()调用的框架上使用.如果您需要重写整个代码以便能够使用异步,那么任何新的Python功能都是没有意义的.

我错过了什么吗?

谢谢!

python python-asyncio

14
推荐指数
3
解决办法
9330
查看次数

标签 统计

python ×1

python-asyncio ×1