Welcome to fstatemachine’s documentation!¶
fstatemachine is a simple finite state machine implementation written in Python. It supports python >= 3.6
Indices and tables¶
Installation¶
pip install fstatemachine
or clone the repo and execute:
python setup.py install
Quickstart¶
from fstatemachine import StateMachine
# Define some states, order is not important
order_states = ['pending', 'awaiting_payment', 'shipped', 'cancelled', 'completed']
# Or with aliases
# order_states = {1: 'pending', 2: 'awaiting_payment', 3: 'shipped', 4 : 'cancelled', 5: 'completed'}
# order_states = [(1, 'pending'), (2, 'awaiting_payment'), (3, 'shipped'), (4, 'cancelled'), (5, 'completed')]
# Define transitions
order_transitions = {
# Order status can be changed from pending to any other state
'pending': '__all__',
# awaiting_payment cannot be changed again to pending, but can be any another
'awaiting_payment': ['shipped', 'cancelled', 'completed'],
# from shipped we can change state only to cancelled or completed
'shipped': ['cancelled', 'completed'],
# we cannot change status from cancelled or completed
# we just didn't specify the dictionary key,
# but this will do the same:
# 'cancelled': None,
# 'completed': [],
}
Now we can play with this example
>>> machine = StateMachine(current='pending', states=order_states, transitions=order_transitions)
>>> # we can check ability to change the state
>>> machine.check('cancelled')
>>> # or we can set new state and check that it is legit in one action
>>> machine.current = 'shipped' # change state from pending to shipped
>>> # this will raise WrongTransition exception
>>> machine.check('pending')
WrongTransition: from shipped to pending
>>> # and this
>>> machine.current = 'awaiting_payment'
WrongTransition: from shipped to awaiting_payment
Package contents¶
The StateMachine class¶
- class fstatemachine.StateMachine(*, current, states, transitions)¶
StateMachine class
- Parameters
current (
Hashable) – initial state of machinestates (
Iterable) – available states. Can be list, dict or list with tuples with state and aliastransitions (
Dict[Hashable,Union[List[Hashable],str,None]]) –transitions between states where key is initial state and value is list of legit states for transition. State can be any hashable object. It will be convenient if the status implements __str__ method.
- Value can be:
list of states for transition
None or empty list for prohibition of transition (or not set key)
”__all__” string for specify that any state are available for transition
- Raises
ValueError
- check(new)¶
Check if new state is valid transitions for machine
- Parameters
new – state for check
- Raises
WrongTransition,ValueError
- property current¶
Current state of machine
The WrongTransition exception¶
- exception fstatemachine.WrongTransition¶
Wrong Transition Error class