我想使用生成器yield和异步函数。我阅读了this topic,并编写了下一段代码:
import asyncio
async def createGenerator():
mylist = range(3)
for i in mylist:
await asyncio.sleep(1)
yield i*i
async def start():
mygenerator = await createGenerator()
for i in mygenerator:
print(i)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(start())
except keyboardInterrupt:
loop.stop()
pass
但我错了:
SyntaxError:异步函数中的“yield”
如何在异步函数中使用yield生成器?
升级版:
从Python 3.6开始,我们有了asynchronous generators,并且能够直接在协程中使用
yield
。Python 3.5的旧答案:
你不能在协程中
yield
。唯一的方法是使用__aiter__
/__anext__
魔术方法手动实现Asynchronous Iterator。就你而言:输出:
这里还有两个例子:1,2
这应该适用于Python3.6(使用3.6.0b1测试):
新的Python3.6支持异步生成器。
PEP 0525
What's new in Python 3.6
PS:在编写Python3.6的时候,它仍然是beta版。如果您在GNU/Linux或OS X上,并且您不能等待,那么您可以使用pyenv尝试新的Python。
相关问题 更多 >
编程相关推荐