statechart package

Submodules

statechart.action module

class statechart.action.Action[source]

Bases: object

execute(metadata, event)[source]

Called by the transition, override for specific behaviour.

Args:
metadata (Metadata): Common statechart metadata. event (Event): The event which triggered this action.
Raises:
Not implemented error for abstract class.
class statechart.action.CallAction(callback)[source]

Bases: statechart.action.Action

Generic action configured with a callback function, executed when the Transition is fired.

Note:

The callback function must be exception safe and support args for the statechart metadata and transition event trigger.

e.g. def callback(self, metadata, event):

execute(metadata, event)[source]

Called by the transition, executes the callback function, passing the statechart metadata and transition event trigger..

Args:
metadata (Metadata): Common statechart metadata. event (Event): The event which triggered this action.

statechart.event module

class statechart.event.Event(name)[source]

Bases: object

An event is a specification of a type of observable occurrence. The occurrence that generates an event instance is assumed to take place at an instant in time with no duration.

Example:

Create an instance of an event: my_event = Event(name=’my event’)

Add the event trigger to a transition: Transition(start=a, end=b, event=my_event)

Fire the event: statechart.dispatch(event=my_event)

If the current state has an outgoing transition associated with the event, it may be fired if the guard condition allows.

Args:
name (str): An identifier for the event.
class statechart.event.KwEvent(name, **kwargs)[source]

Bases: statechart.event.Event

Extension of the Event base class to facilitate passing kwargs with event.

When an event is fired, it’s data is made available to transition guard and actions. If the transition is executed the event data is also made available to state entry, do and exit actions.

Generally, specialised Event classes should be defined to define the data structure as actions & guards need to unpack it.

Example:

Create an instance of an event: my_event = Event(name=’my event’, a=1, b=‘2’, c=[])

Add the event trigger to a transition: Transition(start=a, end=b, event=my_event)

Fire the event: statechart.dispatch(event=my_event)

Args:
name (str): An identifier for the event. **kwargs: Arbitrary keyword arguments.

statechart.guard module

class statechart.guard.CallGuard(callback)[source]

Bases: statechart.guard.Guard

Generic guard configured with a callback function, checked when the Transition is fired.

Note:

The callback function must be exception safe and support args for the statechart metadata and transition event trigger.

e.g. def callback(self, metadata, event):

check(metadata, event)[source]

Called by the transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
The result returned by the callback function.
class statechart.guard.ElseGuard[source]

Bases: statechart.guard.Guard

Simple ‘else’ guard condition which always returns True when checked.

Useful guard for outgoing transitions from Choice Pseudostates to ensure there is at least one path that can be executed.

check(metadata, event)[source]

Called by the transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
True.
class statechart.guard.EqualGuard(a, b)[source]

Bases: statechart.guard.Guard

Check if the two inputs ‘a’ and ‘b’ are equal.

Args:
a: First input. b: Second input.
check(metadata, event)[source]

Called by the transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
The result of the equality check between ‘a’ and ‘b’.
class statechart.guard.Guard[source]

Bases: object

A guard is a boolean expression that is attached to a transition as a fine-grained control over its firing. The guard is evaluated when an event instance is dispatched by the state machine. If the guard is true at that time, the transition is enabled, otherwise, it is disabled.

Guards should be pure expressions without side effects.

Example:

Create a derived class of Guard:

class GreaterThanZero(Guard):
def check(self, event):
return event.value > 0

Add guard to transition:

Transition(start=a, end=b, event=my_event, guard=GreaterThanZero())

Fire the event. If the state has a transition that : statechart.dispatch(Event(name=’my event’, value=10))

check(metadata, event)[source]

Called by the transition, override for specific behaviour

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Note:
Checking a guard should not have any side effects, therefore don’t mutate event parameter data. The evaluation must always be a boolean expression.
Returns:
Boolean result of expression.
Raises:
Not implemented error for abstract class.

statechart.pseudostates module

class statechart.pseudostates.ChoiceState(context)[source]

Bases: statechart.pseudostates.PseudoState

The Choice pseudo-state is used to compose complex transitional path which, which, when reached, result in the dynamic evaluation of the guards of the triggers of its outgoing transitions.

It enables splitting of transitions into multiple outgoing paths.

Args:
context (Context): The parent context that contains this state.
Note:

It must have at least one incoming and one outgoing Transition.

If none of the guards evaluates to true, then the model is considered ill-formed. To avoid this, it is recommended to define one outgoing transition with a predefined “else” guard for every choice vertex.

activate(metadata, event)[source]

Activate the state and dispatch transition to the default state of the composite state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if the state was activated.
add_transition(transition)[source]

Add a transition from this state.

Transitions are checked in the order they are defined.

Args:
transition (Transition): Transition to add.
Raises:
RuntimeError: If transition is invalid.
class statechart.pseudostates.InitialState(context)[source]

Bases: statechart.pseudostates.PseudoState

A special kind of state signifying the source for a single transition to the default state of the composite state.

Args:
context (Context): The parent context that contains this state.
activate(metadata, event)[source]

Activate the state and dispatch transition to the default state of the composite state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if the state was activated.
add_transition(transition)[source]

Add a transition from this state.

An initial state must have a single transition. The transition must not need an event trigger or have a guard condition.

Args:
transition (Transition): Transition to add, must be an external transition.
Raises:
RuntimeError: If transition is invalid, or if transition already exists.
dispatch(metadata, event)[source]

Dispatch transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
True if the transition was executed, False if transition was not triggered for this event or if the guard condition failed.
Raises:
RuntimeError: If the state could not dispatch transition
class statechart.pseudostates.PseudoState(name, context)[source]

Bases: statechart.states.State

A pseudostate is an abstraction that encompasses different types of transient states. They are used, typically, to connect multiple transitions into more complex state transitions paths.

Args:
name (str): An identifier for the model element. context (Context): The parent context that contains this state.
activate(metadata, event)[source]

Activate the state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if the state was activated.
class statechart.pseudostates.ShallowHistoryState(context)[source]

Bases: statechart.pseudostates.PseudoState

activate(metadata, event)[source]

Activate the state and dispatch transition to the default state of the composite state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if the state was activated.

statechart.runtime module

class statechart.runtime.Metadata[source]

Bases: object

Describes runtime specific data of the statechart. The main data is the currently active state. For every active state a StateRuntimeData object is created which stores specific data for the state. This object is allocated only when the state is active, otherwise it is deleted.

activate(state)[source]

Activates a state for this Metadata. If the state is not already active, it will be added and a new StateRuntimeData created.

Args:
state (State): State to activate.
deactivate(state)[source]

Deactivates the state and frees the allocated resources.

Args:
state (State): State to dactivate.
get_history_state(history_state)[source]

Get the last active state when the history state context was deactivated.

Args:
history_state (HistoryState): History state to lookup
Returns:
The most recent state remembered by the specified history state.
has_history_info(history_state)[source]

Check if the active state runtime has history info to restore.

Args:
history_state (HistoryState): History state to lookup.
Returns:
True if the history state has info of a state to be restored.
is_active(state)[source]

Checks whether the given state is active or not.

Args:
state (State): State to check.
Returns:
True if the state is active.
reset()[source]

Resets the metadata object for reuse.

store_history_info(history_state, actual_state)[source]

” Store history for history state when leaving context.

Args:
history_state (HistoryState): History state to store. When this state’s context is
reactivated, the history state can be restored in order to recall the actual state to recall.

actual_state: (State): State to recall.

class statechart.runtime.StateRuntimeData[source]

Bases: object

Holds the runtime specific data for a state in the statechart.

statechart.states module

class statechart.states.CompositeState(name, context)[source]

Bases: statechart.states.Context

A composite state is a state that contains other state vertices (states, pseudostates, etc.).

Args:
name (str): An identifier for the model element. context (Context): The parent context that contains this state.
activate(metadata, event)[source]

Activate the state.

If the transition being activated leads to this state, activate the initial state.

Args:
metadata (Metadata): Common statechart metadata. event: Event which led to the transition into this state.
deactivate(metadata, event)[source]

Deactivate the state.

If this state contains a history state, store the currently active state in history so it can be restored once the history state is activated.

Args:
metadata (Metadata): Common statechart metadata. event: Event which led to the transition out of this state.
dispatch(metadata, event)[source]

Dispatch transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
True if transition executed, False if transition not allowed, due to mismatched event trigger or failed guard condition.
is_finished(metadata)[source]

” Check if the composite state has reached it’s final state.

Args:
metadata (Metadata): Common statechart metadata.
Returns:
True if the composite state is finished.
class statechart.states.ConcurrentState(name, context)[source]

Bases: statechart.states.Context

A concurrent state is a state that contains composite state regions, activated concurrently.

Args:
name (str): An identifier for the model element. context (Context): The parent context that contains this state.
activate(metadata, event)[source]

Activate the state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if state activated, False if already active.
add_region(region)[source]

Add a new region to the concurrent state.

Arsg:
region (CompositeState): Region to add.
deactivate(metadata, event)[source]

Deactivate child states within regions, then overall state.

Args:
metadata (Metadata): Common statechart metadata. event: Event which led to the transition out of this state.
Returns:
True if state deactivated, False if already inactive.
dispatch(metadata, event)[source]

Dispatch transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
True if transition executed, False if transition not allowed, due to mismatched event trigger or failed guard condition.
is_finished(metadata)[source]

” Check if all regions within the concurrent state are finished.

Args:
metadata (Metadata): Common statechart metadata.
Returns:
True if the concurrent state is finished.
class statechart.states.Context(name, context)[source]

Bases: statechart.states.State

Domain of the state. Needed for setting up the hierarchy. This class needn’t be instantiated directly.

Args:
name (str): An identifier for the model element. context (Context): The parent context that contains this state.
class statechart.states.FinalState(context)[source]

Bases: statechart.states.State

A special kind of state signifying that the enclosing composite state or the entire state machine is completed.

A final state cannot have transitions or dispatch other transitions.

Args:
context (Context): The parent context that contains this state.
Raises:
RuntimeError: If the model is ill-formed by attempting to add a transition directly from
the final state.
add_transition(transition)[source]
class statechart.states.State(name, context)[source]

Bases: object

A State is a simple state that has no regions or submachine states.

Args:
name (str): State name used to identify this instance for logging.
A unique name is recommended although not enforced.

context (Context): The parent context that contains this state.

Attributes:
name (str): State name used to identify this instance. context (Context): State’s parent context.
Examples:
  • First create the parent context

statechart = Statechart(name=’statechart’)

  • Then create the states

a = State(name=’a’, context=statechart) b = State(name=’b’, context=statechart)

  • Finally create the transitions between states with any associated

event triggers, actions or guard conditions. Transition(start=a, end=b)

Note:
Do not dispatch a synchronous event within the action (enter, do or exit) functions. If you need to dispatch an event, do so using the async_dispatch function of the statechart.
Raises:
RuntimeError: If the parent context is invalid.
Only a state chart can have no parent context.
activate(metadata, event)[source]

Activate the state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
Returns:
True if the state was activated.
add_transition(transition)[source]

Add a transition from this state.

Transitions with guards are checked first.

Args:
transition (Transition): Transition to add, can be a normal or
internal transition.
Raises:
RuntimeError: If transition is invalid.
deactivate(metadata, event)[source]

Deactivate the state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition out of this state.
Returns:
True if state deactivated, False if already inactive.
dispatch(metadata, event)[source]

Dispatch transition.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Transition event trigger.
Returns:
True if transition executed, False if transition not allowed, due to mismatched event trigger or failed guard condition.
do(metadata, event)[source]

An optional action that is executed whilst this state is active. The execution starts after this state is entered, and stops either by itself, or when the state is exited, whichever comes first.

Starts an async task. When the task is finished, it may fire an event to trigger a state transition. If the task is still in progress when this state is deactivated it will be cancelled.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
entry(metadata, event)[source]

An optional action that is executed whenever this state is entered, regardless of the transition taken to reach the state. If defined, entry actions are always executed to completion prior to any internal activity or transitions performed within the state.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
exit(metadata, event)[source]

An optional action that is executed upon deactivation of this state regardless of which transition was taken out of the state. If defined, exit actions are always executed to completion only after all internal activities and transition actions have completed execution. Initiates cancellation of the state do action if it is still running.

Args:
metadata (Metadata): Common statechart metadata. event (Event): Event which led to the transition into this state.
name = None

Context can be null only for the statechart

class statechart.states.Statechart(name, metadata=None)[source]

Bases: statechart.states.Context

The main entry point for using the statechart framework. Contains all necessary methods for delegating incoming events to the substates.

Args:
name (str): An identifier for the model element. metadata (Metadata): Common statechart metadata.
add_transition(transition)[source]
dispatch(event)[source]

Calls the dispatch method on the current state.

Args:
event (Event): Transition event trigger.
Returns:
True if transition executed.
is_active(state_name)[source]

Check if the state name is active

Args:
state_name (str): State name to check.
Returns:
True if the state name is currently active.
is_finished()[source]

” Check if the statechart has finished

Returns:
True if the statechart has finished.
start()[source]

Initialises the Statechart in the metadata. Sets the start state.

Ensure the statechart has at least an initial state.

Raises:
RuntimeError if the statechart had already been started.
stop()[source]

Stops the statemachine by deactivating statechart and thus all it’s child states.

statechart.transitions module

class statechart.transitions.InternalTransition(state, event=None, guard=None, action=None)[source]

Bases: statechart.transitions.Transition

A transition that executes without exiting or re-entering the state in which it is defined. This is true even if the state machine is in a nested state within this state.

Args:
state (State): The state which owns this transition. The transition executes without
exiting or re-entering this state.

event (Event|str): The event or event name that fires the transition. guard (Guard): A boolean predicate that must be true for the transition to be fired.

It is evaluated at the time the event is dispatched.

action (Action): An optional procedure to be performed when the transition fires.

execute(metadata, event)[source]

Attempt to execute the transition. Evaluate if the transition is allowed by checking the guard condition. If the transition is allowed perform transition action.

Args:
metadata (Metadata): Common statechart metadata. event (Event): The event that fires the transition.
Returns:
True if the transition was executed.
class statechart.transitions.Transition(start, end, event=None, guard=None, action=None)[source]

Bases: object

A transition is a directed relationship between a source state and a target state. It may be part of a compound transition, which takes the state machine from one state configuration to another, representing the complete response of the state machine to a particular event instance.

Args:
start (State): The originating state (or pseudostate) of the
transition.

end (State): The target state (or pseudostate) that is reached when the transition is executed. event (Event|str): The event or event name that fires the transition. guard (Guard): A boolean predicate that must be true for the

transition to be fired. It is evaluated at the time the event is dispatched.
action (Action): An optional procedure to be performed when the
transition fires.
activate = None

Used to store the states that will get de-activated

execute(metadata, event)[source]

Attempt to execute the transition. Evaluate if the transition is allowed by checking the guard condition. If the transition is allowed, deactivate source states, perform transition action and activate all target states.

Args:
metadata (Metadata): Common statechart metadata. event (Event): The event that fires the transition.
Returns:
True if the transition was executed.
is_allowed(metadata, event)[source]

” Check if the transition is allowed.

Args:
metadata (Metadata): Common statechart metadata. event (Event): The event that fires the transition.
Returns:
True if the transition is allowed.

Module contents