如何简化python协程?

问题描述

我真的很想使用python协程来简化我的数据使用者,但是我发现标准实现不是很好:

def printer():
    print('setup')

    try:
        while True:
            data = yield
            print(data)

    except GeneratorExit:
        pass

    print('cleanup')

是否可以使用for循环编写使用者?

def printer():
    print('setup')

    for data in yield_iterator():
        print(data)

    print('cleanup')

我尝试了几种其他方法来封装yieldGeneratorExit的处理,但是,一旦我将yield移到子功能printer()中,我就没有了不再是协程。

您知道用python编写协程的一种优雅方法吗?

解决方法

我终于能够根据plamut的答案建立解决方案: https://stackoverflow.com/a/60118660/11462250

关键是要创建一个等待对象,并在 await

中产生 yields
class Awaitable:
    def __await__(self):
        return (yield)

然后可以这样写:

async def printer(source):
    print('setup')

    async for data in source:
        print(data)

    print('cleanup')