Python Statemachine is an intuitive and powerful library for implementing finite state machines and statecharts. It offers a clean, pythonic, and declarative API for both synchronous and asynchronous Python codebases, supporting advanced features like compound states, parallel regions, history states, and dynamic diagram generation. The library maintains an active development pace with frequent updates and major releases introducing significant new capabilities.
Install & Compatibility
Where this runs
tested against v3.1.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.940 runs
installs and imports cleanly · install 0.0s · import 0.287s · 20MB
glibcpy 3.10–3.940 runs
installs and imports cleanly · install 1.7s · import 0.251s · 21MB
18MB installed
● package 18MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Introduced in v3.0, recommended for new projects and statechart features.
from statemachine import StateChart, State
Main class in v2.x, preserved in v3.x for backward compatibility. Use StateChart for new features.
from statemachine import StateMachine, State
This quickstart defines a `TrafficLightMachine` as a `StateChart` with three states: `green`, `yellow`, and `red`. A `cycle` event transitions the light sequentially. It includes `before_cycle`, `on_enter_red`, and `on_exit_red` methods, which are automatically called during transitions and state entries/exits respectively.
from statemachine import StateChart, State
class TrafficLightMachine(StateChart):
"A traffic light machine"
green = State(initial=True)
yellow = State()
red = State()
cycle = (
green.to(yellow)
| yellow.to(red)
| red.to(green)
)
def before_cycle(self, event: str, source: State, target: State):
return f"Running {event} from {source.id} to {target.id}"
def on_enter_red(self):
print("Don't move.")
def on_exit_red(self):
print("Go ahead!")
sm = TrafficLightMachine()
print(f"Initial state: {sm.current_state.id}")
print(sm.send("cycle"))
print(f"Current state: {sm.current_state.id}")
print(sm.send("cycle"))
print(f"Current state: {sm.current_state.id}")
print(sm.send("cycle"))
print(f"Current state: {sm.current_state.id}")
Upgrade
Version history
Breaking-change detection hasn't run for this library yet.
Audit
Security & dependencies
CVE tracking and dependency tree are planned for a later release.