CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-statemachine

Python finite state machine library with declarative API for sync and async applications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Python StateMachine

A 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.

Package Information

  • Package Name: python-statemachine
  • Language: Python
  • Installation: pip install python-statemachine
  • Optional Dependencies: pip install python-statemachine[diagrams] (for Graphviz diagram generation)

Core Imports

from statemachine import StateMachine, State, Event

For exceptions:

from statemachine.exceptions import TransitionNotAllowed, InvalidStateValue

For mixins and integration:

from statemachine.mixins import MachineMixin

For diagram generation:

from statemachine.contrib.diagram import DotGraphMachine

Basic Usage

from 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']

Architecture

The python-statemachine library follows a decoupled design that separates state machine logic from domain models:

  • StateMachine: Main class that orchestrates states, events, and transitions
  • State: Individual states with entry/exit actions and transition definitions
  • Event: Triggers that initiate state transitions
  • Transition: Connection between states with conditions and actions
  • Engines: Execution engines for sync (SyncEngine) and async (AsyncEngine) support
  • Model Integration: Optional integration with external domain objects via mixins

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.

Capabilities

Core State Machine and States

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: ...

Core State Machine

Events and Transitions

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): ...

Events and Transitions

Actions and Callbacks

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): ...

Actions and Callbacks

Exceptions and Error Handling

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): ...

Exceptions and Error Handling

Mixins and Integration

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 = False

Mixins and Integration

Diagram Generation

Graphical 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): ...

Diagram Generation

Utilities and Data Classes

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): ...

Utilities and Data Classes

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-statemachine@2.5.x
Publish Source
CLI
Badge
tessl/pypi-python-statemachine badge