Transitions
Transitions is a lightweight, object-oriented finite state machine implementation for Python, designed to be easy to use and extend. It supports features like hierarchical states, parallel states, conditional transitions, and callbacks. Currently at version 0.9.3, the library maintains an active development pace with minor releases frequently adding new features, bugfixes, and typing improvements.
Warnings
- breaking The legacy `HierarchicalMachine` implementation was removed in version 0.9.0. Users should migrate to the `NestedState` and `HierarchicalMachine` features available directly via the standard `Machine` class or its `HierarchicalMachine` extension.
- gotcha When using `add_transition` with multiple conditional transitions for the same trigger/source, the order in which transitions are added matters. Transitions are evaluated in the order they were added, and the first one whose conditions evaluate to `True` will be executed.
- gotcha When `queued=True` is enabled for a `Machine`, trigger calls will always return `True` immediately, as there is no way to determine at queuing time if a transition will ultimately complete successfully after processing the queue.
- gotcha Methods assigned as callbacks (e.g., `before`, `after`, `on_enter`, `on_exit`, `conditions`) must be able to handle all arguments that the triggering event passes. This can be problematic if different callbacks expect different data.
- breaking In version 0.8.10, the literal string 'self' (the default model parameter of `Machine`) changed from a value check to an identity check. This affects how `Machine` determines if it should act as its own model.
Install
-
pip install transitions
Imports
- Machine
from transitions import Machine
- State
from transitions import State
Quickstart
from transitions import Machine
class Matter(object):
def __init__(self):
self.state = None # Machine will manage this
def make_hissing_noises(self):
print("HISSSSSSSSSSSSSSSS")
def disappear(self):
print("where'd all the liquid go?")
states = ['solid', 'liquid', 'gas', 'plasma']
transitions = [
{ 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid', 'before': 'make_hissing_noises' },
{ 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas', 'after': 'disappear' },
{ 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
{ 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
]
lump = Matter()
machine = Machine(model=lump, states=states, transitions=transitions, initial='solid')
print(f"Initial state: {lump.state}")
lump.melt()
print(f"Current state: {lump.state}")
lump.evaporate()
print(f"Current state: {lump.state}")