One of my favorite development strategies is using finite state machines. They’re not right for every type of problem but they have greater applicability than you might think. I’ve written several FSM-based applications almost always in C. C isn’t the only possibility, of course. You can write an FSM in nearly any language.
Arpit Bhayani has an interesting post that describes writing FSMs in Python. That language is fairly powerful and offers several possible implementation strategies but Bhayani suggests a particularly nice one: coroutines.
I think of coroutines as being the inverse of generators. Rather than having yield
return a value and suspend executions as generators do, in coroutines, yield
suspends the execution and waits for other code to send
it a value. It’s very much like a blocking read.
Each time the FSM gets a new event, it sends it to the coroutine representing the current state through the send/yield
mechanism. The coroutine uses the event to determine the next state and do whatever processing is necessary for the state transition. Bhayani offers several examples illustrating the technique. Take a look at the post for some actual code.