Roland's homepage

My random knot in the Web

State machines in Python

State machines can be relatively easy defined as a data structure.

It has been said that data structures are central to programming. So we should find a way to express a state machine into a data structure.

The following dictionary of state transitions can be used to define a state machine. The key is a 2-tuple of the input and current state. In Python 3.4+, it would probably be a good idea to make the state into an enum.

transitions = {(inpt, state): (newstate, [output1, output2])}

where:

inpt
is the input,
state
is the current state,
newstate
is the state at the end of the transition,
output1, output2
is an iterable of outputs. These outputs are functions.

The beauty of this transition table is that it contains both states and input, and only valid transitions are defined. If the (inpt, state) tuple does not exist in the transition table, then you know that the combination of input and state is invalid.


For comments, please send me an e-mail.


←  Using gnuplot from Python Structures in Python  →