如何在异步函数中使用"yield"?

编程入门 行业动态 更新时间:2024-10-25 00:36:47
本文介绍了如何在异步函数中使用"yield"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用生成器yield和async函数.我阅读了该主题,并编写了下一个代码:

I want to use generator yield and async functions. I read this topic, and wrote next code:

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'

SyntaxError: 'yield' inside async function

如何在异步函数中使用良率生成器?

How to use yield generator in async function?

推荐答案

更新:

从Python 3.6开始,我们有了异步生成器,并且能够使用yield直接在协程内部.

Starting with Python 3.6 we have asynchronous generators and able to use yield directly inside coroutines.

import asyncio async def async_generator(): for i in range(3): await asyncio.sleep(1) yield i*i async def main(): async for i in async_generator(): print(i) loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.run_until_complete(loop.shutdown_asyncgens()) # see: docs.python/3/library/asyncio-eventloop.html#asyncio.loop.shutdown_asyncgens loop.close()

Python 3.5的旧答案:

您不能在协程内部yield.唯一的方法是实现异步迭代器使用__aiter__/__anext__魔术方法手动进行.就您而言:

You can't yield inside coroutines. Only way is to implement Asynchronous Iterator manually using __aiter__/__anext__ magic methods. In your case:

import asyncio class async_generator: def __init__(self, stop): self.i = 0 self.stop = stop async def __aiter__(self): return self async def __anext__(self): i = self.i self.i += 1 if self.i <= self.stop: await asyncio.sleep(1) return i * i else: raise StopAsyncIteration async def main(): async for i in async_generator(3): print(i) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())

输出:

0 1 4

还有另外两个示例: 1 , 2

Here're two more examples: 1, 2

更多推荐

如何在异步函数中使用"yield"?

本文发布于:2023-11-23 13:49:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   如何在   yield   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!