0

I really would like to use python coroutines to simplify my data consumers, but I find the standard implementation not very elegant:

def printer():
    print('setup')

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

    except GeneratorExit:
        pass

    print('cleanup')

Is there a way to write a consumer by using a for loop?

def printer():
    print('setup')

    for data in yield_iterator():
        print(data)

    print('cleanup')

I tried a few different things to encapsulate yield and the handling of GeneratorExit, but as soon as I move yield into a sub-function printer() isn't recognized as a coroutine anymore.

Do you know of an elegant way to write coroutines in python?

Dave
  • 1

1 Answers1

0

I finally was able to build a solution based on the answer from plamut: https://stackoverflow.com/a/60118660/11462250

The key was to create an awaitable object that yields in await

class Awaitable:
    def __await__(self):
        return (yield)

Then it's possible to write something like this:

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

    async for data in source:
        print(data)

    print('cleanup')
Dave
  • 1