Automaton

3.4.0 · active · verified Fri Apr 17

Automaton is a Python library for creating friendly and declarative state machines. It simplifies the definition and management of states, events, and transitions, making it easy to model complex system behaviors. The current version is 3.4.0, and the project is under active development with periodic releases.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a simple `LightSwitch` state machine with `off` and `on` states and `turn_on`/`turn_off` events. It shows state initialization, event triggering, and how `automaton` handles invalid transitions by raising an `InvalidTransition` exception.

from automaton import StateMachine, State, Event

class LightSwitch(StateMachine):
    # Define states
    off = State("off")
    on = State("on")

    # Define events and transitions
    turn_on = Event(source=off, target=on)
    turn_off = Event(source=on, target=off)

# Instantiate the state machine
switch = LightSwitch()

# Check initial state
print(f"Initial state: {switch.current_state}")

# Trigger events
switch.turn_on()
print(f"After turning on: {switch.current_state}")

try:
    switch.turn_on() # This should fail as it's already on
except Exception as e:
    print(f"Attempting to turn on again (expected error): {e}")

switch.turn_off()
print(f"After turning off: {switch.current_state}")

view raw JSON →