Stackless & String-processing
Greg Ewing
greg.ewing at compaq.com
Thu Jul 15 23:50:45 EDT 1999
Neel Krishnaswami wrote:
>
> What's the difference, exactly? AFAICT you need to save the execution
> state when suspending both coroutines and generators, but I might be
> missing something obvious....
The crucial difference is that a generator is never resumed
after its caller has returned. This means that the generator's
state can be pushed onto the same stack as the caller's.
A coroutine, on the other hand, can outlive the context in
which it was created, and therefore needs a stack all of
its own.
Another way to think about it is that a generator call is
equivalent to an ordinary call where one of the parameters
is a procedure. For example, where in "generator python"
you might write
def even_numbers_up_to(n):
for i in range(n):
if i % 2 == 0:
yield(i)
for e in even_numbers_up_to(42):
print e, "is an even number!"
you could do the same thing in ordinary python as
def for_each_even_number_up_to(n, do_it):
for i in range(n):
if i % 2 == 0:
do_it(i)
def print_it(e):
print e, "is an even number!"
for_each_even_number_up_to(42, print_it)
which clearly can be executed quite happily using
a single stack.
If Python had something akin to Smalltalk code blocks,
generators wouldn't be needed. It would be nifty to
be able to write something like
for_each_even_number_up_to(42) -> (e):
print e, "is an even number!"
Greg
More information about the Python-list
mailing list