n00b question: Better Syntax for Coroutines?

Carl Banks pavlovevidence at gmail.com
Sat Sep 13 01:08:14 EDT 2008


On Sep 12, 9:08 pm, i... at illusorygoals.com wrote:
> First off, I'm a python n00b, so feel free to comment on anything if
> I'm doing it "the wrong way." I'm building a discrete event simulation
> tool. I wanted to use coroutines. However, I want to know if there's
> any way to hide a yield statement.
>
> I have a class that I'd like to look like this:
>
> class Pinger(Actor):
>     def go(self):
>         success = True
>         while success:
>             result = self.ping("128.111.41.38")
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> But because I can't hide yield inside ping, and because I can't find a
> convenient way to get a self reference to the coroutine (which is used
> by the event queue to pass back results), my code looks like this:
>
> class Pinger(Actor):
>     def go(self):
>         # I dislike this next line
>         self.this_pointer = (yield None)
>         success = True
>         while success:
>             # I want to get rid of the yield in the next line
>             result = (yield self.ping("128.111.41.38"))
>             if result != "success":
>                 success = False
>         print "Pinger done"
>
> I'd like to know, is there a way to get the syntax I want?

I think you're stuck with using threads in a standard Python release.
Generators can't serve as coroutines when you're yielding from a
nested call (they only go one level deep).

You can get coroutines with Stackless Python, a non-standard version
of Python.  But even with Stackless I got the impression that you'd be
building coroutines atop something that was fairly thread-like.  There
is no coroutine syntax.


Carl Banks





More information about the Python-list mailing list