# API

## Machines

class automaton.machines.State(name: str, is_terminal: bool = False, next_states: Mapping[str, str] | None = None, on_enter: Callable[[str, str], None] | None = None, on_exit: Callable[[str, str], None] | None = None)

  Container that defines needed components of a single state.

  Usage of this and the `build()` make creating finite state machines that much easier.

  Variables:

    - name – The name of the state.

    - is_terminal – Whether this state is terminal (or not).

    - next_states – Dictionary of ‘event’ -> ‘next state name’ (or none).

    - on_enter – callback that will be called when the state is entered.

    - on_exit – callback that will be called when the state is exited.

class automaton.machines.FiniteMachine

  A finite state machine.

  This state machine can be used to automatically run a given set of transitions and states in response to events (either from callbacks or from generator/iterator send() values, see PEP 342). On each triggered event, a `on_enter` and `on_exit` callback can also be provided which will be called to perform some type of action on leaving a prior state and before entering a new state.

  NOTE(harlowja): reactions will only be called when the generator/iterator from `run_iter()` does not send back a new event (they will always be called if the `run()` method is used). This allows for two unique ways (these ways can also be intermixed) to use this state machine when using `run()`; one where external event trigger the next state transition and one where internal reaction callbacks trigger the next state transition. The other way to use this state machine is to skip using `run()` or `run_iter()` completely and use the `process_event()` method explicitly and trigger the events via some external functionality/triggers…

  class Effect(reaction, terminal)

    The result of processing an event (cause and effect…)

    reaction

      Alias for field number 0

    terminal

      Alias for field number 1

  __contains__(state: str) → bool

    Returns if this state exists in the machines known states.

  __iter__() → Generator[tuple[str, str, str], None, None]

    Iterates over (start, event, end) transition tuples.

  add_reaction(state: str, event: str, reaction: Callable[[...], Any], *args: Any, **kwargs: Any) → None

    Adds a reaction that may get triggered by the given event & state.

    Reaction callbacks may (depending on how the state machine is ran) be used after an event is processed (and a transition occurs) to cause the machine to react to the newly arrived at stable state.

    These callbacks are expected to accept three default positional parameters (although more can be passed in via args and **kwargs, these will automatically get provided to the callback when it is activated *ontop of the three default). The three default parameters are the last stable state, the new stable state and the event that caused the transition to this new stable state to be arrived at.

    The expected result of a callback is expected to be a new event that the callback wants the state machine to react to. This new event may (depending on how the state machine is ran) get processed (and this process typically repeats) until the state machine reaches a terminal state.

  add_state(state: str, terminal: bool = False, on_enter: Callable[[str, str], None] | None = None, on_exit: Callable[[str, str], None] | None = None) → None

    Adds a given state to the state machine.

    The `on_enter` and `on_exit` callbacks, if provided will be expected to take two positional parameters, these being the state being exited (for `on_exit`) or the state being entered (for `on_enter`) and a second parameter which is the event that is being processed that caused the state transition.

  add_transition(start: str, end: str, event: str, replace: bool = False) → None

    Adds an allowed transition from start -> end for the given event.

    Parameters:

      - start – starting state

      - end – ending state

      - event – event that causes start state to transition to end state

      - replace – replace existing event instead of raising a `Duplicate` exception when the transition already exists.

  classmethod build(state_space: Sequence[State | StateDict]) → FiniteMachine

    Builds a machine from a state space listing.

    Each element of this list must be an instance of `State` or a `dict` with equivalent keys that can be used to construct a `State` instance.

  copy(shallow: bool = False, unfreeze: bool = False) → Self

    Copies the current state machine.

    NOTE(harlowja): the copy will be left in an uninitialized state.

    NOTE(harlowja): when a shallow copy is requested the copy will share

      the same transition table and state table as the source; this can be advantageous if you have a machine and transitions + states that is defined somewhere and want to use copies to run with (the copies have the current state that is different between machines).

  property current_state: str | None

    The current state the machine is in (or none if not initialized).

  property default_start_state: str | None

    Sets the default start state that the machine should use.

    NOTE(harlowja): this will be used by `initialize` but only if that function is not given its own `start_state` that overrides this default.

  property events: int

    Returns how many events exist.

  freeze() → None

    Freezes & stops addition of states, transitions, reactions…

  initialize(start_state: str | None = None) → None

    Sets up the state machine (sets current state to start state…).

    Parameters:

      start_state – explicit start state to use to initialize the state machine to. If `None` is provided then the machine’s default start state will be used instead.

  is_actionable_event(event: str) → bool

    Check whether the event is actionable in the current state.

  pformat(sort: bool = True, empty: str = '.') → str

    Pretty formats the state + transition table into a string.

    NOTE(harlowja): the sort parameter can be provided to sort the states and transitions by sort order; with it being provided as false the rows will be iterated in addition order instead.

  process_event(event: str) → Effect

    Trigger a state change in response to the provided event.

    Returns:

      Effect this is either a `FiniteMachine.Effect` or an `Effect` from a subclass of `FiniteMachine`. See the appropriate named tuple for a description of the actual items in the tuple. For example, `FiniteMachine.Effect`’s first item is `reaction`: one could invoke this reaction’s callback to react to the new stable state.

    Return type:

      namedtuple

  property states: list[str]

    Returns the state names.

  property terminated: bool

    Returns whether the state machine is in a terminal state.

class automaton.machines.HierarchicalFiniteMachine

  A fsm that understands how to run in a hierarchical mode.

  class Effect(reaction, terminal, machine)

    The result of processing an event (cause and effect…)

    machine

      Alias for field number 2

    reaction

      Alias for field number 0

    terminal

      Alias for field number 1

  add_state(state: str, terminal: bool = False, on_enter: Callable[[str, str], None] | None = None, on_exit: Callable[[str, str], None] | None = None, machine: FiniteMachine | None = None) → None

    Adds a given state to the state machine.

    Parameters:

      machine – the nested state machine that will be transitioned into when this state is entered

    Further arguments are interpreted as for `FiniteMachine.add_state()`.

  copy(shallow: bool = False, unfreeze: bool = False) → Self

    Copies the current state machine.

    NOTE(harlowja): the copy will be left in an uninitialized state.

    NOTE(harlowja): when a shallow copy is requested the copy will share

      the same transition table and state table as the source; this can be advantageous if you have a machine and transitions + states that is defined somewhere and want to use copies to run with (the copies have the current state that is different between machines).

  initialize(start_state: str | None = None, nested_start_state_fetcher: Callable[[FiniteMachine], str | None] | None = None) → None

    Sets up the state machine (sets current state to start state…).

    Parameters:

      - start_state – explicit start state to use to initialize the state machine to. If `None` is provided then the machine’s default start state will be used instead.

      - nested_start_state_fetcher – A callback that can return start states for any nested machines only. If not `None` then it will be provided a single argument, the machine to provide a starting state for and it is expected to return a starting state (or `None`) for each machine called with. Do note that this callback will also be passed to other nested state machines as well, so it will also be used to initialize any state machines they contain (recursively).

  property nested_machines: dict[str, FiniteMachine]

    Dictionary of all nested state machines this machine may use.

## Runners

class automaton.runners.Runner(machine: FiniteMachine)

  Machine runner used to run a state machine.

  Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

  abstractmethod run(event: str, initialize: bool = True) → None

    Runs the state machine, using reactions only.

  abstractmethod run_iter(event: str, initialize: bool = True) → Generator[tuple[str | None, str | None], Any, None]

    Returns a iterator/generator that will run the state machine.

    NOTE(harlowja): only one runner iterator/generator should be active for a machine, if this is not observed then it is possible for initialization and other local state to be corrupted and cause issues when running…

class automaton.runners.FiniteRunner(machine: FiniteMachine)

  Finite machine runner used to run a finite machine.

  Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

  run(event: str, initialize: bool = True) → None

    Runs the state machine, using reactions only.

  run_iter(event: str, initialize: bool = True) → Generator[tuple[str | None, str | None], Any, None]

    Returns a iterator/generator that will run the state machine.

    NOTE(harlowja): only one runner iterator/generator should be active for a machine, if this is not observed then it is possible for initialization and other local state to be corrupted and cause issues when running…

class automaton.runners.HierarchicalRunner(machine: HierarchicalFiniteMachine)

  Hierarchical machine runner used to run a hierarchical machine.

  Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

  run(event: str, initialize: bool = True) → None

    Runs the state machine, using reactions only.

  run_iter(event: str, initialize: bool = True) → Generator[tuple[str | None, str | None], Any, None]

    Returns a iterator/generator that will run the state machine.

    This will keep a stack (hierarchy) of machines active and jumps through them as needed (depending on which machine handles which event) during the running lifecycle.

    NOTE(harlowja): only one runner iterator/generator should be active for a machine hierarchy, if this is not observed then it is possible for initialization and other local state to be corrupted and causes issues when running…

## Converters

automaton.converters.pydot.convert(machine: FiniteMachine, graph_name: str, graph_attrs: Mapping[str, Any] | None = None, node_attrs_cb: Callable[[str], Mapping[str, Any]] | None = None, edge_attrs_cb: Callable[[str, str, str], Mapping[str, Any]] | None = None, add_start_state: bool = True, name_translations: Mapping[str, str] | None = None) → Any

  Translates the state machine into a pydot graph.

  Parameters:

    - machine – state machine to convert

    - graph_name – name of the graph to be created

    - graph_attrs – any initial graph attributes to set (see http://www.graphviz.org/doc/info/attrs.html for what these can be)

    - node_attrs_cb – a callback that takes one argument `state` and is expected to return a dict of node attributes (see http://www.graphviz.org/doc/info/attrs.html for what these can be)

    - edge_attrs_cb – a callback that takes three arguments `start_state, event, end_state` and is expected to return a dict of edge attributes (see http://www.graphviz.org/doc/info/attrs.html for what these can be)

    - add_start_state – when enabled this creates a private start state with the name `__start__` that will be a point node that will have a dotted edge to the `default_start_state` that your machine may have defined (if your machine has no actively defined `default_start_state` then this does nothing, even if enabled)

    - name_translations – a dict that provides alternative `state` string names for each state

## Exceptions

exception automaton.exceptions.AutomatonException

  Base class for most exceptions emitted from this library.

exception automaton.exceptions.Duplicate

  Raised when a duplicate entry is found.

exception automaton.exceptions.FrozenMachine

  Exception raised when a frozen machine is modified.

exception automaton.exceptions.InvalidState

  Raised when a invalid state transition is attempted while executing.

exception automaton.exceptions.NotFound

  Raised when some entry in some object doesn’t exist.

exception automaton.exceptions.NotInitialized

  Error raised when an action is attempted on a not inited machine.

### Hierarchy

digraph inheritance348b908e00 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "AutomatonException" [URL="#automaton.exceptions.AutomatonException",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Base class for *most* exceptions emitted from this library."]; "Duplicate" [URL="#automaton.exceptions.Duplicate",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Raised when a duplicate entry is found."]; "AutomatonException" -> "Duplicate" [arrowsize=0.5,style="setlinewidth(0.5)"]; "FrozenMachine" [URL="#automaton.exceptions.FrozenMachine",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Exception raised when a frozen machine is modified."]; "AutomatonException" -> "FrozenMachine" [arrowsize=0.5,style="setlinewidth(0.5)"]; "InvalidState" [URL="#automaton.exceptions.InvalidState",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Raised when a invalid state transition is attempted while executing."]; "AutomatonException" -> "InvalidState" [arrowsize=0.5,style="setlinewidth(0.5)"]; "NotFound" [URL="#automaton.exceptions.NotFound",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Raised when some entry in some object doesn't exist."]; "AutomatonException" -> "NotFound" [arrowsize=0.5,style="setlinewidth(0.5)"]; "NotInitialized" [URL="#automaton.exceptions.NotInitialized",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top",tooltip="Error raised when an action is attempted on a not inited machine."]; "AutomatonException" -> "NotInitialized" [arrowsize=0.5,style="setlinewidth(0.5)"]; }
this page last updated: 2026-07-16 04:46:42

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.

found an error? report a bug