Transitions

0.9.3 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates creating a simple state machine with a model, defining states and transitions, and triggering state changes. Callbacks can be attached to transitions (e.g., `before`, `after`) to execute logic.

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}")

view raw JSON →