Generators versus Coroutines

Bernhard Mulder bwm at
Mon Aug 16 18:08:10 CEST 2004

If you want, you can yield across multiple levels by converting 
functions into generators and calls into for loops.

The following function illustrates this approach:

    def ack(m, n):
        if m == 0:
          yield n + 1
       if m > 0 and n == 0:
          for i in ack(m-1, 1):
             yield None
          yield i
       if m > 0 and n > 0:
          for i in ack(m, n-1):
             yield None
          t = i
          for i in ack(m-1, t):
             yield None
          yield i

You call this function this way:

for i in ack(2, 2):
# now i contains the function value.

Paul Rubin wrote:
> Michael Sparks <zathras at> writes:
>>>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)
> You can't yield across multiple levels of function calls.  That's why
> they're called "simple generators" instead of just "generators".

More information about the Python-list mailing list