Skip to main content

sqlalchemy-state-machine

Explicit, typed state transitions for SQLAlchemy models.

Requirements

  • Python 3.11+ (CI validates Python 3.11, 3.12, 3.13, and 3.14)
  • SQLAlchemy 2.x

Install

uv add sqlalchemy-state-machine
pip install sqlalchemy-state-machine

Quick start

Declare a SQLAlchemy 2.x model and its state machine together:

from typing import ClassVar

from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column

from sqlalchemy_state_machine import StateMachine, StateMachineMixin, Transition


class Base(DeclarativeBase):
    pass


class Order(StateMachineMixin, Base):
    __tablename__ = "orders"

    id: Mapped[int] = mapped_column(primary_key=True)
    status: Mapped[str] = mapped_column(nullable=False)

    state_machine: ClassVar[StateMachine] = StateMachine(
        state_attribute="status",
        initial="draft",
        transitions=(
            Transition(name="submit", source="draft", target="submitted"),
            Transition(
                name="cancel",
                source=("draft", "submitted"),
                target="cancelled",
            ),
        ),
    )


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

with Session(engine) as session:
    order = Order()
    assert order.status == "draft"
    assert order.can_transition("submit")
    assert order.available_transitions() == ("submit", "cancel")
    assert order.transition("submit") == "submitted"

    session.add(order)
    session.commit()

transition(name) applies a declared transition and returns its target state. can_transition(name) reports whether a transition is currently available, and available_transitions() returns available names in declaration order. Calling an unknown or unavailable transition raises InvalidTransitionError:

from sqlalchemy_state_machine import InvalidTransitionError

try:
    order.transition("submit")
except InvalidTransitionError:
    pass

Callbacks and transactions

A Transition can define before and after callbacks. Both receive (model, transition). The before callback runs while the model has its source state, the state is then changed, and the after callback runs with the target state. If either callback raises, the model state is restored to its original value and the exception is re-raised.

The library changes only the mapped state attribute. It owns no SQLAlchemy session flush, commit, or rollback; application code controls transaction boundaries.

Migrating from 1.x

2.0 is a breaking rewrite for Python 3.11+ and SQLAlchemy 2.x.

1.x 2.0
StateConfig StateMachine and Transition
StateMixin StateMachineMixin
Manual SQLAlchemy init/load events No longer needed
Dynamic model.set_sent() model.transition("set_sent")
Redundant declared states Inferred from the initial state and transitions
after_state_change Per-transition before and after callbacks

The legacy API and its transitions dependency were removed; update models to the explicit 2.0 API rather than mixing 1.x declarations with 2.0 classes.

Example

Run the standalone example:

uv run python examples/basic_usage.py

Development

uv sync
uv run ruff format --check src tests examples
uv run ruff check src tests examples
uv run mypy src
uv run pytest --cov=sqlalchemy_state_machine
uv build

License

sqlalchemy-state-machine is distributed under the Apache License 2.0.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlalchemy_state_machine-2.0.0.tar.gz (57.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlalchemy_state_machine-2.0.0-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_state_machine-2.0.0.tar.gz.

File metadata

  • Download URL: sqlalchemy_state_machine-2.0.0.tar.gz
  • Upload date:
  • Size: 57.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for sqlalchemy_state_machine-2.0.0.tar.gz
Algorithm Hash digest
SHA256 63bbc133eb503ad4db33a40e753f8c1b622b1e4cd8f1d775faa4d96310b408ed
MD5 f50d51f99158774bf3730371a430d599
BLAKE2b-256 6566db120d31291bb72fb54f58608199aa48dcdc041cb507f519c586d2614907

See more details on using hashes here.

Provenance

The following attestation bundles were made for sqlalchemy_state_machine-2.0.0.tar.gz:

Publisher: publish.yml on bigbag/sqlalchemy-state-machine

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sqlalchemy_state_machine-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sqlalchemy_state_machine-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3528586a9c732af6eab4ede98ca0a26f773af60ccf4c6aea2039e625c028f924
MD5 650176a8110393b2650c43aad125c65d
BLAKE2b-256 1c3117f07158ea8da7713a5b092eb0749cf9c0a314cd1cfa8596d365fd11e745

See more details on using hashes here.

Provenance

The following attestation bundles were made for sqlalchemy_state_machine-2.0.0-py3-none-any.whl:

Publisher: publish.yml on bigbag/sqlalchemy-state-machine

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page