API

StateChart

Added in version 3.0.0.

class statemachine.statemachine.StateChart(model: TModel | None = None, state_field: str = 'state', start_value: Any = None, listeners: List[object] | None = None, **kwargs: Any)[source]
Parameters:
  • model – An optional external object to store state. See Domain models.

  • state_field (str) – The model’s field which stores the current state. Default: state.

  • start_value – An optional start state value if there’s no current state assigned on the Domain models. Default: None.

  • listeners – An optional list of objects that provides attributes to be used as callbacks. See Listeners for more details.

  • **kwargs – Additional keyword arguments available for dependency injection into callbacks. These are passed to class listener setup() methods and to the initial activation callbacks (e.g. on_enter_<state>).

exception TransitionNotAllowed(event: Event | None, configuration: MutableSet[State])

Shortcut alias for easy exception handling.

Example:

try:
    sm.send("an-inexistent-event")
except sm.TransitionNotAllowed:
    pass
activate_initial_state() Any[source]
property active_listeners: List[object]

List of all active listeners attached to this instance.

Includes class-level listeners (resolved from the listeners class attribute), constructor listeners= parameter, and any added via add_listener().

add_listener(*listeners)[source]

Add a listener.

Listener are a way to generically add behavior to a StateChart without changing its internal implementation.

See also

Listeners.

allow_event_without_transition: bool = True

If False when an event does not result in a transition, an exception TransitionNotAllowed will be raised. If True the state machine allows triggering events that may not lead to a state Transitions, including tolerance to unknown Events triggers. Default: True.

property allowed_events: List[Event]

List of the current allowed events.

atomic_configuration_update: bool = False

If False (default), the state machine will follow the SCXML specification, that means in a microstep, it will first exit and execute exit callbacks for all the states in the exit set in reversed document order, then execute the transition content (on callbaks), then enter all the states in the enter set in document order.

If True, the state machine will execute the exit callbacks, the on transition callbacks, then atomically update the configuration of exited and entered states, then execute the enter callbacks.

bind_events_to(*targets)[source]

Bind the state machine events to the target objects.

cancel_event(send_id: str)[source]

Cancel all the delayed events with the given send_id.

catch_errors_as_events: bool = True

If True (default), runtime exceptions in callbacks (guards, actions, entry/exit) produce an error.execution internal event instead of propagating, as mandated by the SCXML specification. If False, exceptions propagate normally.

property configuration: OrderedSet[State]

The set of currently active states.

property configuration_values: OrderedSet[Any]

The state configuration values is the set of currently active states’s values (or ids if no custom value is defined).

property current_state: State | MutableSet[State]

Get/Set the current States.

Deprecated since version 3.0.0: Use configuration / configuration_values instead.

property current_state_value

Get/Set the current States value.

This is a low level API, that can be used to assign any valid state value completely bypassing all the hooks and validations.

enable_self_transition_entries: bool = True

If False (default), when a self-transition is selected, the state entry/exit actions will not be executed. If True, the state entry actions will be executed, which is conformant with the SCXML spec.

enabled_events(*args, **kwargs) Any[source]

List of the current enabled events, considering guard conditions.

An event is enabled if at least one of its transitions from the current state has all cond/unless guards satisfied.

Parameters:
  • *args – Positional arguments forwarded to condition callbacks.

  • **kwargs – Keyword arguments forwarded to condition callbacks.

Returns:

A list of enabled Events instances.

events = []
final_states: List[State]

List of top-level States objects marked as final.

history_values: Dict[str, List[State]]

Mapping from compound state IDs to the list of states that were active the last time that compound state was exited. Used by history pseudo-states to restore previous configurations.

id: str = 'statechart'

Lowercase version of name (e.g. "trafficlightmachine").

initial_state: State | None

The single top-level initial States, or None for abstract classes.

property is_terminated

Whether the state machine has reached a final state.

Returns True when a top-level final state has been entered and the engine is no longer running. This is the recommended way to check for completion – it works for flat, compound, and parallel topologies.

model: TModel

The external model object that holds domain state, or an internal Model instance when none is provided. See Domain models.

name: str = 'StateChart'

The class name of the state machine (e.g. "TrafficLightMachine").

prepare: SpecListGrouper = <statemachine.callbacks.SpecListGrouper object>
raise_(event: str, *args, delay: float = 0, send_id: str | None = None, **kwargs) Any[source]

Send an Events to the state machine in the internal event queue.

Events on the internal queue are processed immediately within the current macrostep, before any pending external events. This is equivalent to calling send(..., internal=True).

See also

See: Triggering events.

send(event: str, *args, delay: float = 0, send_id: str | None = None, internal: bool = False, **kwargs) Any[source]

Send an Events to the state machine.

Parameters:
  • event – The trigger for the state machine, specified as an event id string.

  • args – Additional positional arguments to pass to the event.

  • delay – A time delay in milliseconds to process the event. Default is 0.

  • send_id – An identifier for the event, used with cancel_event() to cancel delayed events.

  • kwargs – Additional keyword arguments to pass to the event.

See also

See: Triggering events.

start_configuration_values: List[Any] = []

Default state values to be entered when the state machine starts.

If empty (default), the root initial state will be used.

states: States = []

Collection of top-level States objects declared on this class.

states_map: Dict[Any, State] = {}

Mapping from each state’s value to the corresponding States instance. Includes states at all nesting levels (compound children, parallel regions, etc.).

StateMachine

class statemachine.statemachine.StateMachine(model: TModel | None = None, state_field: str = 'state', start_value: Any = None, listeners: List[object] | None = None, **kwargs: Any)[source]
allow_event_without_transition: bool = False

If False when an event does not result in a transition, an exception TransitionNotAllowed will be raised. If True the state machine allows triggering events that may not lead to a state Transitions, including tolerance to unknown Events triggers. Default: True.

atomic_configuration_update: bool = True

If False (default), the state machine will follow the SCXML specification, that means in a microstep, it will first exit and execute exit callbacks for all the states in the exit set in reversed document order, then execute the transition content (on callbaks), then enter all the states in the enter set in document order.

If True, the state machine will execute the exit callbacks, the on transition callbacks, then atomically update the configuration of exited and entered states, then execute the enter callbacks.

catch_errors_as_events: bool = False

If True (default), runtime exceptions in callbacks (guards, actions, entry/exit) produce an error.execution internal event instead of propagating, as mandated by the SCXML specification. If False, exceptions propagate normally.

enable_self_transition_entries: bool = False

If False (default), when a self-transition is selected, the state entry/exit actions will not be executed. If True, the state entry actions will be executed, which is conformant with the SCXML spec.

id = 'statemachine'

Lowercase version of name (e.g. "trafficlightmachine").

name = 'StateMachine'

The class name of the state machine (e.g. "TrafficLightMachine").

prepare = <statemachine.callbacks.SpecListGrouper object>
states = []

Collection of top-level States objects declared on this class.

states_map = {}

Mapping from each state’s value to the corresponding States instance. Includes states at all nesting levels (compound children, parallel regions, etc.).

State

See also

States reference.

class statemachine.state.State(name: str = '', value: Any = None, initial: bool = False, final: bool = False, parallel: bool = False, states: List[State] | None = None, history: List[HistoryState] | None = None, enter: Any = None, exit: Any = None, invoke: Any = None, donedata: Any = None, _callbacks: Any = None)[source]

A State in a StateChart describes a particular behavior of the machine. When we say that a machine is “in” a state, it means that the machine behaves in the way that state describes.

Parameters:
  • name – A human-readable representation of the state. Default is derived from the name of the variable assigned to the state machine class, by replacing _ and . with spaces and capitalizing the first word.

  • value – A specific value to the storage and retrieval of states. If specified, you can use It to map a more friendly representation to a low-level value.

  • initial – Set True if the State is the initial one. There must be one and only one initial state in a statemachine. Defaults to False. If not specified, the default initial state is the first child state in document order.

  • final – Set True if represents a final state. A machine can have optionally many final states. Final states have no Transitions starting from It. Defaults to False.

  • enter – One or more callbacks assigned to be executed when the state is entered. See Actions.

  • exit – One or more callbacks assigned to be executed when the state is exited. See Actions.

State is a core component on how this library implements an expressive API to declare StateMachines.

>>> from statemachine import State

Given a few states…

>>> draft = State(name="Draft", initial=True)
>>> producing = State("Producing")
>>> closed = State('Closed', final=True)

Transitions are declared using the State.to() or State.from_() (reversed) methods.

>>> draft.to(producing)
TransitionList([Transition('Draft', 'Producing', event=[], internal=False, initial=False)])

The result is a TransitionList. Don’t worry about this internal class. But the good thing is that it implements the OR operator to combine transitions, so you can use the | syntax to compound a list of transitions and assign to the same event.

You can declare all transitions for a state in one single line …

>>> transitions = draft.to(draft) | producing.to(closed)

… and you can append additional transitions for a state to previous definitions.

>>> transitions |= closed.to(draft)
>>> [(t.source.name, t.target.name) for t in transitions]
[('Draft', 'Draft'), ('Producing', 'Closed'), ('Closed', 'Draft')]

There are handy shortcuts that you can use to express this same set of transitions.

The first one, draft.to(draft), is also called a Self-transitions and internal transitions, and can be expressed using an alternative syntax:

>>> draft.to.itself()
TransitionList([Transition('Draft', 'Draft', event=[], internal=False, initial=False)])

You can even pass a list of target states to declare at once all transitions starting from the same state.

>>> transitions = draft.to(draft, producing, closed)
>>> [(t.source.name, t.target.name) for t in transitions]
[('Draft', 'Draft'), ('Draft', 'Producing'), ('Draft', 'Closed')]

Sometimes it’s easier to use the State.from_() method:

>>> transitions = closed.from_(draft, producing, closed)
>>> [(t.source.name, t.target.name) for t in transitions]
[('Draft', 'Closed'), ('Producing', 'Closed'), ('Closed', 'Closed')]
class Compound[source]

Uses the class namespace to build a States instance of a compound state

class Parallel[source]

Uses the class namespace to build a States instance of a parallel state

property from_: _FromState

Create transitions from the given target states (reversed).

property to: _ToState

Create transitions to the given target states.

HistoryState

Added in version 3.0.0.

class statemachine.state.HistoryState(name: str = '', value: Any = None, type: str | HistoryType = HistoryType.SHALLOW)[source]

States (class)

class statemachine.states.States(states: Dict[str, State] | None = None)[source]

A class representing a collection of States objects.

Helps creating StateChart’s States definitions from other sources, like an Enum class, using States.from_enum().

>>> states_def = [('open', {'initial': True}), ('closed', {'final': True})]
>>> from statemachine import StateChart
>>> class SM(StateChart):
...
...     states = States({
...         name: State(**params) for name, params in states_def
...     })
...
...     close = states.open.to(states.closed)

And states can be used as usual.

>>> sm = SM()
>>> sm.send("close")
>>> sm.closed.is_active
True
__init__(states: Dict[str, State] | None = None) None[source]

Initializes a new instance of the States class.

Parameters:

states – A dictionary mapping keys as State.id and values States instances.

Returns:

None.

classmethod from_enum(enum_type: Type[Enum], initial, final=None, use_enum_instance: bool = True)[source]

Creates a new instance of the States class from an enumeration.

Consider an Enum type that declares our expected states:

>>> class Status(Enum):
...     pending = 1
...     completed = 2

A StateChart that uses this enum can be declared as follows:

>>> from statemachine import StateChart
>>> class ApprovalMachine(StateChart):
...
...     _ = States.from_enum(Status, initial=Status.pending, final=Status.completed)
...
...     finish = _.pending.to(_.completed)
...
...     def on_enter_completed(self):
...         print("Completed!")

Tip

When you assign the result of States.from_enum to a class-level variable in your StateChart, you’re all set. You can use any name for this variable. In this example, we used _ to show that the name doesn’t matter. The metaclass will inspect the variable of type States (class) and automatically assign the inner States instances to the state machine.

Everything else is similar, the Enum is only used to declare the States instances.

>>> sm = ApprovalMachine()
>>> sm.pending.is_active
True
>>> sm.send("finish")
Completed!
>>> sm.completed.is_active
True
>>> sm.current_state_value
<Status.completed: 2>

If you need to use the raw enum value instead of the enum instance, you can set use_enum_instance=False:

>>> states = States.from_enum(Status, initial=Status.pending, use_enum_instance=False)
>>> states.completed.value
2

Changed in version 3.0.0: The default changed from False to True.

Parameters:
  • enum_type – An enumeration containing the states of the machine.

  • initial – The initial state of the machine.

  • final – A set of final states of the machine.

  • use_enum_instance – If True, the value of the state will be the enum item instance, otherwise the enum item value. Defaults to True.

Returns:

A new instance of the States (class).

items()[source]

Returns a view object of the states, with pairs of (State.id, State).

Parameters:

None.

Returns:

A view object of the items in the the instance.

Transition

See also

Transitions reference.

class statemachine.transition.Transition(source: State, target: State | List[State] | None = None, event=None, internal=False, initial=False, validators=None, cond=None, unless=None, on=None, before=None, after=None)[source]

A transition holds reference to the source and target state.

Parameters:
  • source (State) – The origin state of the transition.

  • target – The target state(s) of the transition. Can be a single State, a list of states (for multi-target transitions, e.g. SCXML parallel region entry), or None (targetless transition).

  • event (Optional[Union[str, List[str]]]) – List of designators of events that trigger this transition. Can be either a list of strings, or a space-separated string list of event descriptors.

  • internal (bool) – Is the transition internal or external? Internal transitions don’t execute the state entry/exit actions. Default False.

  • validators (Optional[Union[str, Callable, List[Callable]]]) – The validation callbacks to be invoked before the transition is executed.

  • cond (Optional[Union[str, Callable, List[Callable]]]) – The condition callbacks to be invoked before the transition is executed that should evaluate to True.

  • unless (Optional[Union[str, Callable, List[Callable]]]) – The condition callbacks to be invoked if the cond is False before the transition is executed.

  • on (Optional[Union[str, Callable, List[Callable]]]) – The callbacks to be invoked when the transition is executed.

  • before (Optional[Union[str, Callable, List[Callable]]]) – The callbacks to be invoked before the transition is executed.

  • after (Optional[Union[str, Callable, List[Callable]]]) – The callbacks to be invoked after the transition is executed.

is_self

Is the target state the same as the source state?

property target: State | None

Primary target state (first target for multi-target transitions).

property targets: List[State]

All target states. For single-target transitions, returns a one-element list.

TransitionList

class statemachine.transition_list.TransitionList(transitions: Iterable[Transition] | None = None)[source]

A list-like container of Transitions with callback functions.

__getitem__(index: int) Transition[source]

Returns the Transitions at the specified index.

Parameters:

index – The index of the transition.

Returns:

The Transitions at the specified index.

__init__(transitions: Iterable[Transition] | None = None)[source]
Parameters:

transitions – An iterable of Transition objects. Defaults to None.

__len__()[source]

Returns the number of transitions in the TransitionList instance.

Returns:

The number of transitions.

__or__(other: TransitionList | Iterable)[source]

Return a new TransitionList that combines the transitions of this TransitionList with another TransitionList or iterable.

Parameters:

other – Another TransitionList or iterable of Transitions objects.

Returns:

A new TransitionList object that combines the

transitions of this TransitionList with other.

Return type:

TransitionList

__repr__()[source]

Return a string representation of the TransitionList.

add_event(event: str)[source]

Adds an event to all transitions in the TransitionList instance.

Parameters:

event – The name of the event to be added.

add_transitions(transition: Transition | TransitionList | Iterable)[source]

Adds one or more transitions to the TransitionList instance.

Parameters:

transition – A sequence of transitions or a TransitionList instance.

Returns:

The updated TransitionList instance.

property unique_events: List[Event]

Returns a list of unique event names across all transitions in the TransitionList instance.

Returns:

A list of unique event names.

Model

See also

Domain models reference.

class statemachine.model.Model[source]
state

Holds the current States value of the StateChart.

TriggerData

class statemachine.event_data.TriggerData(machine: 'StateChart', event: 'Event | None', send_id: 'str | None' = None, execution_time: float = 0.0, args: tuple = <factory>, kwargs: dict = <factory>)[source]
args: tuple

All positional arguments provided on the Events.

event: Event | None

The Event that was triggered.

execution_time: float = 0.0

The time at which the Events should run.

future: Any = None

An optional asyncio.Future for async result routing.

When set, the processing loop will resolve this future with the microstep result (or exception), allowing the caller to await it.

kwargs: dict

All keyword arguments provided on the Events.

model: Any

A reference to the underlying model that holds the current States.

send_id: str | None = None

A string literal to be used as the id of this instance of TriggerData.

Allow revoking a delayed TriggerData instance.

Event

class statemachine.event.Event(transitions: str | Transition | TransitionList | None = None, id: str | None = None, name: str | None = None, delay: float = 0, internal: bool = False, _sm: StateChart | None = None)[source]

An event triggers a signal that something has happened.

They are sent to a state machine and allow the state machine to react.

An event starts a Transitions, which can be thought of as a “cause” that initiates a change in the state of the system.

See also Events.

__call__(*args, **kwargs) Any[source]

Send this event to the current state machine.

Triggering an event on a state machine means invoking or sending a signal, initiating the process that may result in executing a transition.

id: str

The event identifier.

name: str

The event name.

EventData

class statemachine.event_data.EventData(trigger_data: statemachine.event_data.TriggerData, transition: 'Transition')[source]
source: State

The States which StateChart was in when the Event started.

state: State

The current States of the StateChart.

target: State | None

The destination States of the Transitions, or None for targetless.

transition: Transition

The Transitions instance that was activated by the Events.

trigger_data: TriggerData

The TriggerData of the Events.

Callback conventions

These are convention-based callbacks that you can define on your state machine subclass. They are not methods on the base class — define them in your subclass to enable the behavior.

prepare_event

Called before every event is processed. Returns a dict of keyword arguments that will be merged into **kwargs for all subsequent callbacks (guards, actions, entry/exit handlers) during that event’s processing:

class MyMachine(StateChart):
    initial = State(initial=True)
    loop = initial.to.itself()

    def prepare_event(self):
        return {"request_id": generate_id()}

    def on_loop(self, request_id):
        # request_id is available here
        ...

MachineMixin

See also

Integrations for usage examples.

class statemachine.mixins.MachineMixin(*args, **kwargs)[source]

This mixing allows a model to automatically instantiate and assign an StateMachine.

bind_events_as_methods: bool = False

If True the state machine events triggers will be bound to the model as methods.

state_field_name: str = 'state'

The model’s state field name that will hold the state value.

state_machine_attr: str = 'statemachine'

Name of the model’s attribute that will hold the machine instance.

state_machine_name: str | None = None

A fully qualified name of the class, where it can be imported.

create_machine_class_from_definition

Added in version 3.0.0.

statemachine.io.create_machine_class_from_definition(name: str, states: Mapping[str, StateKwargs | StateDefinition], **definition) type[StateChart][source]

Create a StateChart class dynamically from a dictionary definition.

Parameters:
  • name – The class name for the generated state machine.

  • states – A mapping of state IDs to state definitions. Each state definition can include initial, final, parallel, name, value, enter/exit callbacks, donedata, nested states, history, and transitions via on (event-triggered) or transitions (eventless).

  • **definition – Additional keyword arguments passed to the metaclass (e.g., validate_final_reachability=False).

Returns:

A new StateChart subclass configured with the given states and transitions.

Example:

>>> machine = create_machine_class_from_definition(
...     "TrafficLightMachine",
...     **{
...         "states": {
...             "green": {"initial": True, "on": {"change": [{"target": "yellow"}]}},
...             "yellow": {"on": {"change": [{"target": "red"}]}},
...             "red": {"on": {"change": [{"target": "green"}]}},
...         },
...     }
... )

timeout

Added in version 3.0.0.

See also

State timeouts how-to guide.

statemachine.contrib.timeout.timeout(duration: float, *, on: str | None = None) _Timeout[source]

Create a timeout invoke handler.

Parameters:
  • duration – Time in seconds to wait before firing.

  • on – Event name to send when the timeout expires. If None, the standard done.invoke.<state> event fires via invoke completion.

Returns:

An IInvoke-compatible handler.

Raises:

ValueError – If duration is not positive.