TypeError from Python 3 async for loop

妖精的绣舞 提交于 2021-02-05 09:35:20

问题


I'm learning about Python's relatively new async features. I found this in PEP 492:

The following is a utility class that transforms a regular iterable to an asynchronous one. While this is not a very useful thing to do, the code illustrates the relationship between regular and asynchronous iterators.

class AsyncIteratorWrapper:
    def __init__(self, obj):
        self._it = iter(obj)

    def __aiter__(self):
        return self

    async def __anext__(self):
        try:
            value = next(self._it)
        except StopIteration:
            raise StopAsyncIteration
        return value

async for letter in AsyncIteratorWrapper("abc"):
    print(letter)

I attempted to run this code, by adding the given async for loop to a function, and then calling that using an event loop.

Full example code (run in the interpreter):

class AsyncIteratorWrapper:
    def __init__(self, obj):
        self._it = iter(obj)
    def __aiter__(self):
        return self
    async def __anext__(self):
        try:
            value = next(self._it)
        except StopIteration:
            raise StopAsyncIteration
        return value

async def aprint(str):
  async for letter in AsyncIteratorWrapper(str):
    print(letter)

import asyncio
loop = asyncio.get_event_loop()
co = aprint("abcde")
loop.run_until_complete(co)

However, I'm getting an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/base_events.py", line 337, in run_until_complete
    return future.result()
  File "/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "<stdin>", line 2, in aprint
TypeError: 'async for' received an invalid object from __aiter__: AsyncIteratorWrapper

What am I doing wrong? How can this example be fixed? I'm a little surprised that code right out of the PEP is failing.

I'm using python version 3.5.1.


回答1:


The code you are using works with python 3.5.2+.

From Python 3.5.2 __aiter__ can directly return asynchronous iterators. More here

The error you were receiving was because of the older python(3.5.1) and it was therefore returning the wrong type.



来源:https://stackoverflow.com/questions/42635790/typeerror-from-python-3-async-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!