Skip to content

About

A small, dependency-free declarative finite state machine for Python: states, transitions, guards and callbacks

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

Repository files navigation

statemachine

CI Python 3.10+ Core: no dependencies License: MIT

A dependency-free declarative finite state machine for Python — and Flowforge, a workflow engine and dashboard built on it. Define a workflow as states and transitions, run instances of it, and fire events that are guarded, applied and recorded, with a live diagram showing where every instance stands.

  • The library — declare states and transitions, fire events, with guards that gate a move and callbacks that run on it. Zero dependencies.
  • Flowforge — the same machine as a service: workflows defined as data, durable running instances, an audit trail of every transition, an SVG diagram of the machine, and a REST API + dashboard. The web layer is an optional [web] extra; the core stays dependency-free.

Flowforge — the workflow engine

Turn the library into a running service. Define a workflow once (as JSON), then start instances and drive them with events. Every move is checked against the definition, persisted, and added to the instance's history; the current state and the path taken are shown on a generated diagram.

A running workflow instance in Flowforge

Quickstart

pip install "statemachine-lite[web]"
statemachine serve                       # dashboard + API at http://localhost:8000

The dashboard seeds a few example workflows (order fulfilment, document review, a bug ticket) so there is something to explore immediately.

Define a workflow as data

A workflow is a name, an initial state, and transitions. A transition names a trigger, a source (one state, a list, or "*" for any), a dest, and optionally requires — data fields that must be supplied when the event is fired (a simple, declarative guard).

{
  "name": "Order fulfilment",
  "initial": "cart",
  "transitions": [
    { "trigger": "checkout", "source": "cart",   "dest": "placed" },
    { "trigger": "pay",      "source": "placed", "dest": "paid",    "requires": ["payment_ref"] },
    { "trigger": "ship",     "source": "paid",   "dest": "shipped", "requires": ["tracking"] },
    { "trigger": "deliver",  "source": "shipped","dest": "delivered" },
    { "trigger": "cancel",   "source": ["placed", "paid"], "dest": "cancelled" }
  ]
}

Drive it from code

from statemachine import WorkflowEngine, WorkflowStore

engine = WorkflowEngine(WorkflowStore("flows.db"))
workflow = engine.define(definition)              # validates and stores it
order = engine.start(workflow.id, "Order #1024")  # a new instance at "cart"

engine.fire(order.id, "checkout")
engine.fire(order.id, "pay", {"payment_ref": "PAY-88213"})
engine.available(order.id)                         # ["pack", "cancel"]
engine.fire(order.id, "pay")                        # TransitionError: a required field is missing

Firing is durable: the engine rebuilds the machine at the instance's stored state, applies the transition (honouring requires guards), saves the new state, and appends to the instance's history — so the whole lifecycle is auditable.

REST API

The dashboard is a thin layer over the same engine; every view has a JSON counterpart.

GET  /                              dashboard
POST /workflows                     create a workflow { definition: <json> }
GET  /workflows/{id}                workflow page (with a diagram)
GET  /workflows/{id}.json           definition + instances
POST /workflows/{id}/instances      start an instance
GET  /instances/{id}                instance page (current state highlighted, actions, history)
GET  /instances/{id}.json           state, available actions and history
POST /instances/{id}/fire           fire a trigger { trigger, <required fields> }

Diagram anything

The SVG renderer is standalone — no Graphviz:

statemachine diagram order.json -o order.svg

Docker

docker build -t flowforge .
docker run -p 8000:8000 -v "$PWD/data:/data" flowforge      # workflows persist in /data

The core library

from statemachine import StateMachine

turnstile = StateMachine(initial="locked")
turnstile.add_transition("coin", "locked", "unlocked")
turnstile.add_transition("push", "unlocked", "locked")

turnstile.trigger("coin")   # "unlocked"
turnstile.trigger("push")   # "locked"
turnstile.trigger("push")   # raises TransitionError: no transition from "locked"

Why

Any workflow with distinct states and rules about how you move between them — an order, a document, a connection, a game — is a state machine, and writing those rules as scattered if statements gets unmanageable fast. This library lets you declare the states and transitions in one place, with guards that gate a transition and callbacks that run on it, and it refuses invalid moves instead of silently allowing them. It is intentionally small and has no dependencies.

Features

  • Declarative transitions: add_transition(trigger, source, dest), with source as a single state, a list, or "*" for any state.
  • Guards: a transition can carry one or more predicates; it only fires if they all pass. Firing passes event data (trigger, source, dest, and any keyword arguments) to guards and callbacks.
  • Callbacks: on_enter/on_exit per state and action per transition, run in the order exit → action → enter.
  • Introspection: can(trigger) tests whether a move is allowed now; triggers() lists the events available from the current state.
  • Safe by default: an invalid trigger raises TransitionError and leaves the state unchanged.

Declarative definitions

For the data-driven path (which Flowforge uses), WorkflowDefinition round-trips a machine through JSON and build_machine turns it into a live StateMachine:

from statemachine import WorkflowDefinition, build_machine

defn = WorkflowDefinition.from_dict(definition)
machine = build_machine(defn)          # or build_machine(defn, current="paid") to resume

Testing

pip install -e ".[dev]"
ruff check .
pytest

Forty-two tests: the state machine itself (transitions, invalid moves, guards, callback ordering, wildcards); the declarative definition layer and its validation; the SVG diagram renderer; the SQLite store; the workflow engine (start, fire, guards, history, invalid moves); and the FastAPI service (creating workflows, starting instances, firing actions, the JSON API, 404s) via TestClient. CI runs ruff and the suite on Python 3.10 through 3.13.

Project layout

src/statemachine/machine.py      the StateMachine, states, transitions and EventData (the core)
src/statemachine/definition.py   declarative, JSON-serialisable workflow definitions
src/statemachine/diagram.py      a dependency-free SVG renderer for a workflow
src/statemachine/store.py        SQLite persistence for workflows, instances and history
src/statemachine/engine.py       the workflow engine: define, start, fire, history
src/statemachine/service.py      FastAPI dashboard + REST API ([web] extra)
src/statemachine/cli.py          `statemachine serve` and `statemachine diagram`
tests/                           pytest suite

Future work

  • Nested/hierarchical states, and timed/automatic transitions (deadlines).
  • Per-transition webhooks so a workflow can drive external systems.
  • A visual editor for building definitions in the browser.

License

MIT

About

A small, dependency-free declarative finite state machine for Python: states, transitions, guards and callbacks

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages