Python finite state machine library with declarative API for sync and async applications
npx @tessl/cli install tessl/pypi-python-statemachine@2.5.0A comprehensive and intuitive finite state machine library designed for both synchronous and asynchronous Python applications. It offers a pythonic and expressive API for implementing state machines with basic components (States, Events, Transitions), action handlers, conditional transitions with guards and validators, and full async/await support.
pip install python-statemachinepip install python-statemachine[diagrams] (for Graphviz diagram generation)from statemachine import StateMachine, State, EventFor exceptions:
from statemachine.exceptions import TransitionNotAllowed, InvalidStateValueFor mixins and integration:
from statemachine.mixins import MachineMixinFor diagram generation:
from statemachine.contrib.diagram import DotGraphMachinefrom statemachine import StateMachine, State
class TrafficLightMachine(StateMachine):
"A traffic light state machine"
# Define states
green = State(initial=True)
yellow = State()
red = State()
# Define transitions
cycle = (
green.to(yellow)
| yellow.to(red)
| red.to(green)
)
# Define actions
def before_cycle(self, event: str, source: State, target: State, message: str = ""):
message = ". " + message if message else ""
return f"Running {event} from {source.id} to {target.id}{message}"
def on_enter_red(self):
print("Don't move.")
def on_exit_red(self):
print("Go ahead!")
# Create and use the state machine
sm = TrafficLightMachine()
# Send events
result = sm.send("cycle") # Returns: "Running cycle from green to yellow"
sm.cycle() # Alternative way to trigger event
# Check current state
print(sm.current_state.id) # "yellow"
print(sm.yellow.is_active) # True
# Iterate over states and events
state_ids = [s.id for s in sm.states] # ['green', 'yellow', 'red']
event_ids = [e.id for e in sm.events] # ['cycle']The python-statemachine library follows a decoupled design that separates state machine logic from domain models:
This design enables controlled state transitions with comprehensive testing coverage, correctness guarantees through compile-time validations, and flexible integration patterns for workflow management, order processing, and any application requiring robust state-driven behavior.
Fundamental state machine functionality including StateMachine class definition, State objects with initial/final flags, state transitions, and basic state management operations.
class StateMachine:
def __init__(self, model=None, state_field: str = "state", start_value=None, rtc: bool = True, allow_event_without_transition: bool = False, listeners=None): ...
def send(self, event: str, *args, **kwargs): ...
@property
def current_state(self) -> State: ...
@property
def states(self) -> States: ...
@property
def events(self) -> list: ...
class State:
def __init__(self, name: str = None, value=None, initial: bool = False, final: bool = False, enter=None, exit=None): ...
def to(self, *states, **kwargs) -> TransitionList: ...
def from_(self, *states, **kwargs) -> TransitionList: ...
@property
def is_active(self) -> bool: ...Event handling and state transition management including event triggers, transition definitions with conditions, guards and validators, and transition lifecycle callbacks.
class Event(str):
def __init__(self, name: str = None): ...
@property
def transitions(self) -> TransitionList: ...
class Transition:
def __init__(self, source: State, target: State, event=None, internal: bool = False, validators=None, cond=None, unless=None, on=None, before=None, after=None): ...Lifecycle hooks, action handlers, callback registration, and dependency injection for state machine events including entry/exit actions, transition callbacks, and custom event handlers.
def before_{event}(self, event: str, source: State, target: State, **kwargs): ...
def after_{event}(self, event: str, source: State, target: State, **kwargs): ...
def on_enter_{state}(self, **kwargs): ...
def on_exit_{state}(self, **kwargs): ...Error scenarios, exception types, and error handling patterns including transition validation errors, invalid state values, and configuration errors.
class StateMachineError(Exception): ...
class TransitionNotAllowed(StateMachineError): ...
class InvalidStateValue(StateMachineError): ...
class InvalidDefinition(StateMachineError): ...Domain model integration patterns, mixin classes for automatic state machine binding, and framework integration including Django support and model field binding.
class MachineMixin:
state_field_name: str = "state"
state_machine_name: str = None
state_machine_attr: str = "statemachine"
bind_events_as_methods: bool = FalseGraphical representation and visualization features including Graphviz diagram generation, state machine visualization, and diagram customization options.
class DotGraphMachine:
def __init__(self, machine: StateMachine): ...
def create_digraph(self) -> pydot.Dot: ...
def quickchart_write_svg(sm: StateMachine, path: str): ...Additional utility classes, data structures, and helper functions that support state machine operations including event data handling, model integration, and internal state management.
@dataclass
class TriggerData:
machine: StateMachine
event: Event
args: tuple = field(default_factory=tuple)
kwargs: dict = field(default_factory=dict)
class Events:
def add(self, events): ...
def match(self, event: str) -> bool: ...
def qualname(cls) -> str: ...
def ensure_iterable(obj): ...