Finite state machine in python

Hendrik van Rooyen hendrik at microcorp.co.za
Sun Sep 13 12:09:18 CEST 2009


On Saturday 12 September 2009 22:39:10 Peng Yu wrote:
> Hi,
>
> I have see some discussion on the implementation of finite state
> machine in python. Can somebody point to me the best way in implenting
> an FSM in python?
>
> http://code.activestate.com/recipes/146262/

You can go a long way with a far simpler model than the one in that recipe:

1) Define a routine for every state.
2) Have every state do the following:
     (i) Run the code to make the side effects like outputs happen.
    (ii) Scan the conditions for the state transitions relevant to this state.
          (Only the arrows leaving this state on the state diagram.)
    (iii) Return the next state (either the same or a different state).

3) The main loop of a long running machine then looks like this:

next_state = start_state()

while True:
    next_state = next_state()
    time.sleep(step_time)		# if needed

This simple model is surprisingly powerful, and it can be expanded to run a 
bundle of such machines in parallel very easily, by keeping a list of 
next_states and continuously cycling through and updating the list.

You do not even need a dispatch dictionary.

This is about the simplest model for making FSMs that I know of.
Not sure if it is the "best" - best for what?.

- Hendrik




More information about the Python-list mailing list