Mark Gritter (markgritter) wrote,
Mark Gritter
markgritter

Python coroutines

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.
Tags: programming, python
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 4 comments