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.

Release files for sqlalchemy-state-machine 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sqlalchemy-state-machine 2.0.0
File Size Uploaded
sqlalchemy_state_machine-2.0.0.tar.gz 57.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sqlalchemy-state-machine 2.0.0
File Interpreter ABI Platform
sqlalchemy_state_machine-2.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 67.9 kB

Release files / sqlalchemy_state_machine-2.0.0.tar.gz

Download URL sqlalchemy_state_machine-2.0.0.tar.gz
Size 57.8 kB
Tags Source
SHA-256 checksum
How to use checksums
63bbc133eb503ad4db33a40e753f8c1b622b1e4cd8f1d775faa4d96310b408ed
BLAKE2b-256 checksum
How to use checksums
6566db120d31291bb72fb54f58608199aa48dcdc041cb507f519c586d2614907
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 20, 2026.

Transparency log

Release files / sqlalchemy_state_machine-2.0.0-py3-none-any.whl

Download URL sqlalchemy_state_machine-2.0.0-py3-none-any.whl
Size 10.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3528586a9c732af6eab4ede98ca0a26f773af60ccf4c6aea2039e625c028f924
BLAKE2b-256 checksum
How to use checksums
1c3117f07158ea8da7713a5b092eb0749cf9c0a314cd1cfa8596d365fd11e745
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 20, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files

1.11.0

2 release files

1.9.0

2 release files

1.8.0

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.3

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page