Generators versus Coroutines
bwm at acm.org
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):
if m > 0 and n > 0:
for i in ack(m, n-1):
t = i
for i in ack(m-1, t):
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 thwackety.com> 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