State Machines in Python

Stefan Behnel stefan_ml at behnel.de
Sat Sep 4 14:46:54 EDT 2010


D'Arcy J.M. Cain, 04.09.2010 20:30:
> On Sat, 04 Sep 2010 13:58:00 -0400
> Roy Smith<roy at panix.com>  wrote:
>>> while True:
>>>      state = state(data)
>>
>> This is the pattern I've always used.  Simple and effective for any
>> state machine which is small enough to code by hand.  I generally have
>> my state methods return (next_state, output) tuples, but that's a detail.
>
> What is "output" for?  Is it a string or something else?  What do you
> do with it?  Notice that I create a dictionary which is passed around
> so that states can pass whatever information back that they deem useful
> and any state can pick up whatever info it needs.  for example, in my
> sample code every state uses the counter but only two states use the
> flag element.

I guess the idea is that each of the states can't arbitrarily modify the 
global status (dict) but is restricted to designating a next state and 
returning something. So you don't take the risk of introducing side effects 
somewhere because all state implementations are pure functions (at least as 
far as the state machine itself is concerned).

Stefan




More information about the Python-list mailing list