异步生成器说它没有实现 __anext__,当它实现时

Jam*_*all 3 python async-await python-asyncio

第一次使用 Aync 生成器。我正在使用Python 3.9。

这是我的实现:

import asyncio

class SubEventStream():
    def __init__(self) -> None:
        self.queue = asyncio.Queue()
        return

    async def __aiter__(self):
        return self

    async def __anext__(self):
        return await self.pop()

    async def append(self, request):
        return await self.queue.put(request)

    async def pop(self):
        r = await self.queue.get()
        self.queue.task_done()
        return r

def create_append_tasks(ls, q):
    return [
        asyncio.create_task(q.append(i))
        for i in ls
    ]

async def append_tasks(q):
    tasks = create_append_tasks(('a', 'b', 'c', 'd', 'e'), q)
    return await asyncio.gather(*tasks)


async def run():
    q = SubEventStream()
    await append_tasks(q)

    async for v in q:
        print(v)

asyncio.run(run())
Run Code Online (Sandbox Code Playgroud)

令人困惑的是,这是我不断得到的结果:

/tmp/tmp.ie3Dj7Q9hn/test.py:37: RuntimeWarning: coroutine 'SubEventStream.__aiter__' was never awaited
  async for v in q:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "test.py", line 40, in <module>
    asyncio.run(run())
  File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "test.py", line 37, in run
    async for v in q:
TypeError: 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
Run Code Online (Sandbox Code Playgroud)

显然我确实实施了__anext__。有什么好坚持的?

mkr*_*er1 8

__aiter__必须是常规方法,而不是async方法:

def __aiter__(self):
    return self
Run Code Online (Sandbox Code Playgroud)

请参阅:https ://docs.python.org/3.9/reference/datamodel.html#asynchronous-iterators