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
- property active_listeners: List[object]¶
List of all active listeners attached to this instance.
Includes class-level listeners (resolved from the
listenersclass attribute), constructorlisteners=parameter, and any added viaadd_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
- allow_event_without_transition: bool = True¶
If
Falsewhen an event does not result in a transition, an exceptionTransitionNotAllowedwill be raised. IfTruethe 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 = 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.
- catch_errors_as_events: bool = True¶
If
True(default), runtime exceptions in callbacks (guards, actions, entry/exit) produce anerror.executioninternal event instead of propagating, as mandated by the SCXML specification. IfFalse, exceptions propagate normally.
- 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_valuesinstead.
- 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/unlessguards satisfied.- Parameters:
*args – Positional arguments forwarded to condition callbacks.
**kwargs – Keyword arguments forwarded to condition callbacks.
- Returns:
A list of enabled Events instances.
- events = []¶
- 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.
- property is_terminated¶
Whether the state machine has reached a final state.
Returns
Truewhen 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
Modelinstance 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
initialstate will be used.
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
Falsewhen an event does not result in a transition, an exceptionTransitionNotAllowedwill be raised. IfTruethe 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 anerror.executioninternal event instead of propagating, as mandated by the SCXML specification. IfFalse, 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.
- name = 'StateMachine'¶
The class name of the state machine (e.g.
"TrafficLightMachine").
- prepare = <statemachine.callbacks.SpecListGrouper object>¶
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
Trueif theStateis the initial one. There must be one and only one initial state in a statemachine. Defaults toFalse. If not specified, the default initial state is the first child state in document order.final – Set
Trueif represents a final state. A machine can have optionally many final states. Final states have no Transitions starting from It. Defaults toFalse.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()orState.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
ORoperator 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')]
- 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.
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
Enumclass, usingStates.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.idand 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
Statesclass from an enumeration.Consider an
Enumtype 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_enumto 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
Enumis 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
FalsetoTrue.- 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 toTrue.
- 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), orNone(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?
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:
- 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.
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]¶
-
- future: Any = None¶
An optional
asyncio.Futurefor async result routing.When set, the processing loop will resolve this future with the microstep result (or exception), allowing the caller to
awaitit.
- 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
Nonefor 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
Truethe 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/exitcallbacks,donedata, nestedstates,history, and transitions viaon(event-triggered) ortransitions(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 standarddone.invoke.<state>event fires via invoke completion.
- Returns:
An
IInvoke-compatible handler.- Raises:
ValueError – If duration is not positive.