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?