Monday, March 30, 2009

Coroutines in Python

David Beazley gave a tutorial at coroutines at PyCon 2009.  The slides and code are available for download.  I took them home with me on the plane.  I had a fun time reading the slides and studying the code.  It's a remarkably clear explanation of how generators can be used as coroutines, starting with Python 2.5.  He runs through a good collection of examples, winding up with a simple OS-style task scheduler for cooperative multi-tasking coroutines.

One of his concluding points was really helpful for me.  I found it hard to pay a lot of attention to the evolution of PEP 342, which added coroutine support for generators.  I found it confusing that yield / generators were being extended to handle different use cases.  David clarifies it in a helpful way:
There are three main uses of yield
  • Iteration (a producer of data)
  • Receiving messages (a consumer)
  • A trap (cooperative multitasking)
Do NOT write generator functions that try to do more than one of these at once

No comments: