Python coroutines

Mar 10, 2013 22:43

I learned today that python generators can be run in reverse to create coroutines. The basic idiom is:

def myCoroutine():
while True:
x = (yield)
doSomethingTo( x )

Then you can use it by calling .send() to provide the return value of the yield expression. See a short course here: http://dabeaz.com/coroutines/

This sort of structure is very useful when you want to create a pipeline of operations, some of which (but not all) can be batched. (A sufficiently smart compiler could even put the operations in different threads.) It's possible to build quite complex flows in this way, with each coroutine having multiple sources and sinks.

python, programming

Previous post Next post
Up