Automat Finite State Machines

25.4.16 · active · verified Thu Apr 09

Automat provides a declarative, self-service API for defining finite-state machines directly within your Python classes. It helps manage complex state transitions and actions in a structured, testable way. The current version is 25.4.16, and it maintains a relatively stable release cadence with minor updates and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple state machine for a door with 'closed' and 'open' states, and 'open_door'/'close_door' inputs. It also shows how to associate outputs (actions) with state transitions and how to initialize and interact with the machine.

from automat import MethodicalMachine

class Door(object):
    _machine = MethodicalMachine()

    @_machine.state()
    def closed(self):
        "The door is closed."

    @_machine.state()
    def open(self):
        "The door is open."

    @_machine.input()
    def open_door(self):
        "Open the door."

    @_machine.input()
    def close_door(self):
        "Close the door."

    @_machine.output()
    def _actuallyOpen(self):
        print("The door opens.")

    @_machine.output()
    def _actuallyClose(self):
        print("The door closes.")

    closed.upon(open_door, enter=open, outputs=[_actuallyOpen])
    open.upon(close_door, enter=closed, outputs=[_actuallyClose])

    def __init__(self):
        # Crucial: Initialize the machine with an initial state
        self._machine.initial(self, self.closed)

# Example usage:
d = Door()
print(f"Initial state: {d._machine.current_state(d)._name}")
d.open_door()
print(f"After open_door: {d._machine.current_state(d)._name}")
d.close_door()
print(f"After close_door: {d._machine.current_state(d)._name}")

view raw JSON →