Help with coroutine-based state machines?

Terry Reedy tjreedy at
Tue Jun 3 23:43:28 CEST 2003

"Alan Kennedy" <alanmk at> wrote in message
news:3EDD05FA.CDE86800 at

After reading your response to my response to your essay, I think we
can combine ideas and converge on the following essentials, with
implementation details left out:

Traditionally, execution frames form a linear stack.  With generators,
there can also be a 'pool' of detached, suspended, ready-to-go frames
that are not currently on the stack.

The interpreter executes the code attached to the top frame of the
stack.  That code can bury its frame by calling another function,
whose frame gets put on top.  Or it can unbury the frame underneath by
returning (or yielding), so that its frame get detached and deleted
(or not).  But it cannot directly replace itself (or its frame), such
as with a co-routine call.

However, we can similate such co-routine frame switching as follows:
write a set of 'state' generators, giving each knowledge of the others
it needs to know about.  Instead of having them yield data (pass data
through attributes or globals instead ), have them yield the generator
method corresponding to the next state.  Then support this set of
state methods with a servant dispatch method/frame that sits under the
changing top frame and that helps the state methods 'in effect' call
each other by calling the state method yielded by each state on behalf
of that yielding state.

While mechanically the same, this is conceptually different from the
typical generator usage in which the caller decides on the sequence of
calls.  By making the caller a servant, control is effectively passes
to the callees.

Terry J. Reedy

More information about the Python-list mailing list