Automaton
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
-
automaton.exceptions.InvalidTransition: Event 'event_name' cannot transition from state 'current_state'.
cause Attempting to trigger an `Event` from a state that is not specified as its `source` state in the state machine definition.fixReview your state machine definition and ensure that the `source` state for the triggered event matches the machine's `current_state`. Design your events and state transitions to handle all valid paths. -
ModuleNotFoundError: No module named 'automaton'
cause The `automaton` library is not installed in your current Python environment or is not accessible on the Python path.fixInstall the library using `pip install automaton`. If using a virtual environment, ensure it is activated before installation. -
ERROR: Package 'automaton' requires a different Python version: >=3.10
cause You are attempting to install or run `automaton` on a Python version older than 3.10, which is not supported.fixUpgrade your Python environment to 3.10 or newer. You can use `pyenv` or `conda` to manage multiple Python versions, or create a virtual environment with a compatible Python version.
Warnings
- gotcha Events defined without a specific `source` state (`source=None` or omitted) can transition from *any* state. This can lead to unexpected behavior if strict, explicit transitions are intended.
- gotcha Directly manipulating the `_current_state` attribute is discouraged and bypasses important logic. All state changes should occur via defined `Event` objects to ensure hooks, validations, and listeners are properly invoked.
- gotcha Automaton requires Python 3.10 or newer. Attempting to install or run the library on older Python versions will result in installation failures or runtime errors.
Install
-
pip install automaton
Imports
- StateMachine
from automaton import StateMachine
- State
from automaton import State
- Event
from automaton import Event
Quickstart
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}")