问题描述
我正在学习Python的相对较新的异步功能.我在 PEP 492 中找到了它:
I'm learning about Python's relatively new async features. I found this in PEP 492:
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)
我试图运行此代码,方法是将给定的 async for
循环添加到函数中,然后使用事件循环进行调用.
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
我做错了什么?这个例子怎么解决?PEP之外的代码失败了,我感到有些惊讶.
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.
我正在使用python 3.5.1版本.
I'm using python version 3.5.1.
推荐答案
您正在使用的代码适用于python 3.5.2 +.
The code you are using works with python 3.5.2+.
从Python 3.5.2开始, __ aiter __
可以直接返回异步迭代器.在此处更多
From Python 3.5.2 __aiter__
can directly return asynchronous iterators. More here
您收到的错误是由于使用较旧的python(3.5.1),因此返回错误的类型.
The error you were receiving was because of the older python(3.5.1) and it was therefore returning the wrong type.
这篇关于来自Python 3异步for循环的TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!