Generators versus Coroutines

Nick Patavalis npat at efault.net
Sun Aug 15 00:32:57 CEST 2004


On 2004-08-14, Michael Sparks <zathras at thwackety.com> wrote:
> On 14 Aug 2004, Timothy Fitz wrote:
>
>> It seems to me that in python, generators are not truly coroutines.
>
> Assuming you mean there isn't available a default scheduler for them, or
> there isn't pre-emption built-in I agree. If you mean something else, I'm
> curious as to what you think is missing. (I've also been using generators
> as co-routines for sometime for various reasons)
>

I may be mistaken, as it has been some time since I've last dealt with
coroutines, but aren't you supposed to be able to do this with real
coroutines?

   def baz():
      ...
      for i in range(10):
          yield i
      ...

   def bar():
      ...
      baz()
      ...

   def foo():
      ...
      bar()
      ...

   c = coroutine(foo)
   c.run()

And when baz() yields, you're thrown back to the point where c.run()
was called. How is this possible with generators?

/npat



More information about the Python-list mailing list