send() to a generator in a "for" loop with continue(val)??

Dale Roberts gooberts at gmail.com
Sun Apr 19 23:57:54 CEST 2009


On Apr 19, 6:10 am, Peter Otten <__pete... at web.de> wrote:
> ...
> I only just started reading Beazley's presentation, it looks interesting.
> Thanks for the hint!
>
> Are you currently using coroutines in Python? If so, what kind of practical
> problems do they simplify for you?

I thought I'd chime in with an application too. I am using this
mechanism to implement a state machine. I read through Beazley's
presentation too - wow, lots of ideas in there.

For my simple state machine, I am using a very simple "trampoline"
function (see his slides starting at about #172). My "run" routine is
a bit different, but the idea is similar.

I'm using this to present images to a test subject (a person looking
at a computer screen), and the person's responses guide the state
machine. So I need to get data in (the subject responses) and out (the
next image to be presented).

So I have violated The Beazley Principle of slide #195:

            Keeping it Straight
  • If you are going to use coroutines, it is critically
    important to not mix programming paradigms
    together
  • 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

...whoops!

But I think this is a valid use of the mechanism, in that it is very
localized and self contained to just the few routines that make up the
state machine. It works very well, makes it easy to implement the
state machine clearly, and is easy to understand and maintain.

I can see where it could get very confusing to use this mechanism in a
more general way.

dale



More information about the Python-list mailing list