小编Dyl*_*lee的帖子

如何在不阻塞事件循环的情况下迭代大列表

我有一个运行 asyncio 事件循环的 python 脚本,我想知道如何在不阻塞事件循环的情况下迭代一个大列表。从而保持循环运行。

我试着做一个自定义类__aiter__,并__anext__没有工作,我也试着做一个async function能产生结果,但它仍然块。

目前:

for index, item in enumerate(list_with_thousands_of_items):
    # do something
Run Code Online (Sandbox Code Playgroud)

我试过的自定义类:

class Aiter:
    def __init__(self, iterable):
        self.iter_ = iter(iterable)

    async def __aiter__(self):
        return self

    async def __anext__(self):
        try:
            object = next(self.iter_)
        except StopIteration:
            raise StopAsyncIteration
        return object
Run Code Online (Sandbox Code Playgroud)

但这总是导致

TypeError: 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
Run Code Online (Sandbox Code Playgroud)

async function我做了事件循环是一种作品,但仍块:

TypeError: 'async for' received an object from __aiter__ that does not implement …
Run Code Online (Sandbox Code Playgroud)

python asynchronous list python-3.x python-asyncio

5
推荐指数
1
解决办法
987
查看次数

标签 统计

asynchronous ×1

list ×1

python ×1

python-3.x ×1

python-asyncio ×1