Python finite state machine


A finite state machine (FSM) is a mathematical model of computation with states, transitions, inputs and outputs. This machine is always in a one state at the time and can move to other states using transitions. A transition changes the state of the machine to another state.

A large number of problems can be modeled using finite state machines. Simple examples of state machines used in modern life are vending machines, elevators and traffic lights.  Advanced usage are artificial intelligence, language parsing and communication protocol design.

Related course
Complete Python Bootcamp: Go from zero to hero in Python

Finite State Machine Example

First install the Fysom module:

sudo pip install fysom

We can define a Finite State Machine (FSM) with two states: sleeping and awake.  To move between the states we will define the transitions wakeup() and sleep().

finite state machine

Finite state machine. States: awake, sleeping. Transitions: sleep, wake up


from fysom import *
fsm = Fysom({'initial': 'awake',
             'final': 'red',
             'events': [
                 {'name': 'wakeup', 'src': 'sleeping', 'dst': 'awake'},
                 {'name': 'sleep',  'src': 'awake',   'dst': 'sleeping'}]})
print(fsm.current)   # awake
print(fsm.current)   # sleeping
print(fsm.current)   # awake



Finite State Machines

There are several implementations of Finite State Machines in Python:

Python graph
Python tree
This entry was posted in Beginner and tagged , , . Bookmark the permalink.