python logo

python state machine


Python hosting: Host, run, and code Python in the cloud!

A finite state machine (FSM) represents a computational model characterized by states, transitions, inputs, and outputs. The machine occupies a singular state at any given moment and can transition to other states. A transition is what alters the machine’s current state.

Finite state machines offer solutions to a plethora of problems. In our daily lives, we encounter FSMs in vending machines, elevators, and traffic lights. More complex applications include artificial intelligence, parsing languages, and designing communication protocols.

Related course: Python Programming Bootcamp: Go from zero to hero.

Finite State Machine Example

To get started with building a Finite State Machine in Python, you first need to install the Fysom module:

1
sudo pip install fysom

Following the installation, let’s create a FSM with two potential states: ‘sleeping’ and ‘awake’. The transitions between these states will be the methods wakeup() and sleep().

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

Here’s an illustrative example in Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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) # Output: awake
fsm.sleep()
print(fsm.current) # Output: sleeping
fsm.wakeup()
print(fsm.current) # Output: awake

The output of the above code will be:

1
2
3
awake
sleeping
awake

Finite State Machines in Python

For those interested in diving deeper, there are several Python libraries dedicated to implementing Finite State Machines. A couple of noteworthy mentions include:






Leave a Reply: