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

2024-10-02 22:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用生成器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生成器?


Tags: 函数inloopasyncioforasynctopicdef
3条回答

升级版:

从Python 3.6开始,我们有了asynchronous generators,并且能够直接在协程中使用yield

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: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.shutdown_asyncgens
    loop.close()

Python 3.5的旧答案:

你不能在协程中yield。唯一的方法是使用__aiter__/__anext__魔术方法手动实现Asynchronous Iterator。就你而言:

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

这里还有两个例子:12

这应该适用于Python3.6(使用3.6.0b1测试):

import asyncio

async def createGenerator():
    mylist = range(3)
    for i in mylist:
        await asyncio.sleep(1)
        yield i*i

async def start():
    async for i in createGenerator():
        print(i)

loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(start())

except KeyboardInterrupt:
    loop.stop()
    pass

新的Python3.6支持异步生成器。

PEP 0525

What's new in Python 3.6

PS:在编写Python3.6的时候,它仍然是beta版。如果您在GNU/Linux或OS X上,并且您不能等待,那么您可以使用pyenv尝试新的Python。

相关问题 更多 >