A bundle of questions from a Python newbie

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Feb 21 04:33:00 EST 2002


Gonçalo Rodrigues <op73418 at mail.telepac.pt> wrote in 
news:pk687ugc5s0uhs5h7v3bf3r2q8v4tl7bhi at 4ax.com:

> 12. This is not exactly about Python, but about programming in general.
> I keep reading about continuations and coroutines and I would like to
> know, in simple terms if possible, what the heck are they and in what
> ways they differ from generators as they exist in Python.

The main differences between a coroutine and a generator are:

1) Coroutines maintain their own stack. This allows a coroutine to yield 
not just from the function you originally called, but also from any nested 
function no matter how deep.
Python's generators can only yield directly from the generator as they do 
not attempt to maintain any kind of stack.

BUT, this is misleading. If you want to split a generator function up into 
smaller functions, say to make the code clearer, you can do this provided 
all the smaller functions are also generators and the outer generator calls 
them in a for loop and immediately yields out. So although a generator 
doesn't have an explicit stack maintained by the Python runtime, you can 
nest generators so that they behave in a very similar way to coroutines.

2) Coroutines allow you to pass arguments in each time they are activated 
whereas generators only take arguments when they are created. There is a 
conceptual difference here as coroutines are more peer to peer but 
generators have more of a parent (the caller) and child (the generator) 
relationship. Probably the best way to pass values in to a generator is to 
pass it an iterator as an argument, but this may not be as convenient as 
passing a value directly.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list