Help with coroutine-based state machines?

Alan Kennedy alanmk at hotmail.com
Fri May 30 09:47:49 EDT 2003


Steven Taschuk wrote:

> [Much good advice on appropriate use of generators elided]

> Moreover, when the state functions are generators, you can write
> "states" such as
> 
>     def foo(self):
>         for nextstate in [self.state0, self.state1, self.state2]:
>             yield nextstate
> 
> But this is not a state in the normal sense of "state machine";
> each time you reach this "state", the machine's behaviour is
> different, due solely to differences in the history of execution
> (instead of due to, e.g., differences in input, which would be
> legitimate).  The real state of the machine is the combination of
> the states of all of the iterators.

Had you said this to me a month ago, I wouldn't have had a clue what
you were talking about. But now I understand, and I agree that what I
coded could be "dangerous" for, say, someone trying to debug the code
and who does not understand how the history of execution and the
resumption of "states" affects the current state of the machine.

But if that principle is correct, i.e. that "states" in a "machine"
should not have "after-effects", then surely that same argument could
be applied to the concept of coroutines as a whole? 

At some level, every object/module/codeobject+data is a state-machine.
But objects that use coroutines have "after-effects", so they perhaps
should not be used to implement state-machines (i.e. objects). Hmmm.

How to resolve this paradox?

>> Which is why python generators are only "semi"-coroutines, as
>> opposed to full coroutines. Because, without a dispatcher function,
>> you can only yield control to the calling function, rather than any
>> resumable state that you have a reference to. [...]

> In part, yes.  But even with the dispatcher, you can't call
> another function and have *it* transfer control to another
> coroutine, suspending the whole call stack.  (Not transparently,
> anyway; it could be done by replacing all calls to functions with
> yields to a dispatcher.)

I don't understand.

But I think I need to work through and code a good few examples
before I'll be in a position to know what I don't understand, and
before I could ask meaningful questions.

Thanks much.

kind regards,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list