Stackless Python and Python 2.x

Tim Peters tim.one at home.com
Sun Sep 2 15:19:22 EDT 2001


[Tim]
> ...
> It's unclear how far PEP 255's "Simple Generators" can be pushed
> towards those specific ends [full coroutines and microthreads].

[Gordon McMillan]
> Alas, not far enough. I've used Stackless a number of times to
> turn state machines inside out (where the number of events is
> smallish but the state stuff is complex, this is a wonderful
> simplification). Generally this means that there's a whole
> set of frames hanging around when I "yield".

It remains unclear.  Simple Generators can handle arbitrarily long chains of
frames fine, via making each routine in the chain a Simple Generator and
having each suspend to its invoker (that's how, e.g., every example of
recursive generators works, but there's nothing essential in such examples
about each frame in the chain being associated with the same code block).
That much can be done with Icon/CLU style generators/iterators too.

We can push harder, though:  at the top level, a controller routine can keep
the head (or tail, depending on how you look at it) frame alive for each of
any number of such chains, and resume any at will.

# Map events to primary handlers.
resume_generator_chain = {EVENT_HAPPY:  happy_driver().next,
                          EVENT_SAD:    sad_driver().next,
                          EVENT_BORED:  bored_driver().next}
# "Event loop"
while 1:
    e = get_an_event()
    resume_generator_chain[e]()

Adding the ability to explicitly resume added a lot of power to these guys,
but exactly *how* much isn't known.

>> Neil Schemenauer discovered that it was possible to code the
>> "traditional" coroutine examples using simple generators instead...

> Yah, well your "traditional" thread example prints the numbers
> 1 through 10 twice in some interleaving...

I meant specifically the compare-tree-fringe, and the Dahl & Hoare Simula 67
"squasher", examples.





More information about the Python-list mailing list