# Python state machine libraries

Python state machine libraries model an object's behavior as a fixed set of states and the transitions between them. A machine accepts only the transitions its definition allows and runs callbacks when the state changes. These libraries keep order workflows, Django models, and AI agent loops in a known state at every step.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Automat](#automat-library) | 14.8M | 651 | Apr 2025 | MIT |
| [Python StateMachine](#python-statemachine) | 3.2M | 1.3K | Oct 2026 | MIT |
| [transitions](#transitions) | 2.0M | 6.6K | Jul 2025 | MIT |
| [Django FSM-2](#django-fsm-two) | 668.6K | 287 | Oct 2026 | MIT |
| [Django FSM](#django-fsm) | 553.8K | 2.3K | Nov 2026 | AGPL-3.0-or-later WITH viewflow-library-exception |
| [fysom](#fysom) | 91.8K | 398 | Sep 2021 | MIT |
| [Automaton](#automaton) | 90.2K | 62 | Aug 2026 | Apache-2.0 |
| [Sismic](#sismic) | 6.6K | 172 | Oct 2026 | LGPL-3.0 |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Automat](#automat-library) has the most monthly downloads in this comparison, at 14.8M.

## Capabilities

| Library | Django model integration | Hierarchical states | Awaits coroutine callbacks |
| --- | --- | --- | --- |
| [Automat](#automat-library) | No | Undocumented | No |
| [Python StateMachine](#python-statemachine) | Yes | Yes | Yes |
| [transitions](#transitions) | Via plugin | Yes | Yes |
| [Django FSM-2](#django-fsm-two) | Yes | Undocumented | No |
| [Django FSM](#django-fsm) | Yes | Undocumented | No |
| [fysom](#fysom) | No | Undocumented | Undocumented |
| [Automaton](#automaton) | No | Yes | No |
| [Sismic](#sismic) | No | Yes | Undocumented |

## Libraries

### Automat

[GitHub](https://github.com/glyph/automat) · [PyPI](https://pypi.org/project/automat) · [Docs](https://automat.readthedocs.io/)

Builds finite-state machines.

- Downloads / mo: 14.8M
- Stars: 651
- Last release: 25.4.16
- License: MIT
- Capabilities: [From the Automat docs](https://automat.readthedocs.io/)

```sh
pip install automat
```

**Quickstart**

```python
from typing import Protocol
from automat import TypeMachineBuilder

class Inputs(Protocol):
    def finish(self) -> None: ...

builder = TypeMachineBuilder(Inputs, object)
start = builder.state('start')
done = builder.state('done')
@start.upon(Inputs.finish).to(done)
def finish(controller: Inputs, data: object) -> None:
    pass
machine = builder.build()(object())
machine.finish()

```

From [tutorial.rst](https://automat.readthedocs.io/en/latest/tutorial.html) · [Find projects using Automat →](https://dashboard.exa.ai/playground/search?q=automat%20GitHub%20projects)

### Python StateMachine

[GitHub](https://github.com/fgmacedo/python-statemachine) · [PyPI](https://pypi.org/project/python-statemachine) · [Docs](https://pypi.org/project/python-statemachine/)

Defines declarative state machines and statecharts for synchronous and asynchronous Python.

- Downloads / mo: 3.2M
- Stars: 1.3K
- Last release: 3.2.2
- License: MIT
- Capabilities: [From the Python StateMachine docs](https://pypi.org/project/python-statemachine/)

**Strengths**

- **Declares workflows as Python classes.** Express states, transitions, and guards together in a machine class.
- **Detects async callbacks automatically.** Use the same event API with an automatically selected async engine.

**Watch out for**

- **Thread sharing needs synchronization.** Protect a shared machine instance when callbacks run across multiple threads.

```sh
pip install python-statemachine
```

**ArjanCodes/examples** (1.3K stars)

[ArjanCodes/examples](https://github.com/ArjanCodes/examples) 

```python
def main() -> None:
    payment = PaymentMachine()

    print_configuration(payment)

    payment.authorize(Decimal("49.95"))
    print_configuration(payment)

    payment.capture()
    print_configuration(payment)
```

[2026/libraries/05_state_machine.py](https://github.com/ArjanCodes/examples/blob/ab66e16c6379227b604c15ccb8e4fbcd9df3862d/2026/libraries/05_state_machine.py) · [More projects using Python StateMachine →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20python-statemachine%20for%20workflow%20transitions%2C%20state%20guards%2C%20connection%20lifecycles%20and%20event-driven%20processing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from statemachine import StateChart, State

class Switch(StateChart):
    off = State(initial=True)
    on = State()
    turn_on = off.to(on)

switch = Switch()
switch.send('turn_on')

```

From [README.md](https://pypi.org/pypi/python-statemachine/3.2.2/json#info.description)

### transitions

[GitHub](https://github.com/pytransitions/transitions) · [PyPI](https://pypi.org/project/transitions) · [Docs](https://pypi.org/project/transitions/)

Defines object-oriented finite state machines with optional extension classes.

- Downloads / mo: 2.0M
- Stars: 6.6K
- Last release: 0.9.3
- License: MIT
- Capabilities: [From the transitions docs](https://pypi.org/project/transitions/)

**Strengths**

- **Binds transitions to existing models.** Attach states, triggers, and callbacks to application objects.
- **Combines hierarchy and async callbacks.** Choose the matching machine extension for nested states and asynchronous processing.

**Watch out for**

- **Queued success means accepted.** A queued trigger returns True before its eventual transition outcome is known.

```sh
pip install transitions
```

**allenai/alexafsm** (112 stars)

[allenai/alexafsm](https://github.com/allenai/alexafsm) 

```python
def __init__(self, states: States, request: dict = None, with_graph: bool = False):
    self.states = states
    self.state = states.attributes.state
    state_names, transitions = type(states).get_states_transitions()
    machine_cls = \
        importlib.import_module('transitions.extensions').GraphMachine if with_graph else \
        importlib.import_module('transitions').Machine
    self.machine = machine_cls(
        model=self,
        states=state_names,
        initial=states.attributes.state,
        auto_transitions=False
    )

    for transition in transitions:
        self.machine.add_transition(**transition)
```

[alexafsm/policy.py](https://github.com/allenai/alexafsm/blob/0c2e8842ddbb4a34ac64a5139e7febee3b28889a/alexafsm/policy.py#L25-L40) · [More projects using transitions →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20transitions%20for%20workflow%20transitions%2C%20state%20guards%2C%20connection%20lifecycles%20and%20event-driven%20processing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from transitions import Machine
machine = Machine(states=['a', 'b'], initial='a')
machine.add_transition('advance', 'a', 'b')
machine.advance()

```

From [README.md](https://github.com/pytransitions/transitions)

### Django FSM-2

[GitHub](https://github.com/django-commons/django-fsm-2) · [PyPI](https://pypi.org/project/django-fsm-2) · [Docs](http://github.com/django-commons/django-fsm-2)

Adds finite state machine support to Django.

- Downloads / mo: 668.6K
- Stars: 287
- Last release: 4.3.0
- License: MIT
- Capabilities: [From the Django FSM-2 docs](http://github.com/django-commons/django-fsm-2)

```sh
pip install django-fsm-2
```

**Quickstart**

```python
from django.db import models
from django_fsm import FSMField, FSMModelMixin, transition

class Article(FSMModelMixin, models.Model):
    state = FSMField(default='draft')
    @transition(field=state, source='draft', target='published')
    def publish(self):
        pass

article = Article()
article.publish()

```

From [README.md](https://pypi.org/pypi/django-fsm-2/4.3.0/json#info.description) · [Find projects using Django FSM-2 →](https://dashboard.exa.ai/playground/search?q=django-fsm-2%20GitHub%20projects)

### Django FSM

[GitHub](https://github.com/viewflow/django-fsm) · [PyPI](https://pypi.org/project/django-fsm) · [Docs](https://pypi.org/project/django-fsm/)

Adds state machines to Python objects and Django models.

- Downloads / mo: 553.8K
- Stars: 2.3K
- Last release: 5.0.2
- License: AGPL-3.0-or-later WITH viewflow-library-exception
- Capabilities: [From the Django FSM docs](https://pypi.org/project/django-fsm/)

```sh
pip install django-fsm
```

**Quickstart**

```python
from django_fsm import State

class Review:
    state = State(states=None, default='draft')
    @state.transition(source='draft', target='published')
    def publish(self):
        pass

review = Review()
review.publish()

```

From [README.rst](https://pypi.org/pypi/django-fsm/5.0.2/json#info.description) · [Find projects using Django FSM →](https://dashboard.exa.ai/playground/search?q=django-fsm%20GitHub%20projects)

### fysom

[GitHub](https://github.com/mriehl/fysom) · [PyPI](https://pypi.org/project/fysom) · [Docs](https://pypi.org/project/fysom/)

Implements finite state machines in Python.

- Downloads / mo: 91.8K
- Stars: 398
- Last release: 2.1.6
- License: MIT
- Capabilities: [From the fysom docs](https://pypi.org/project/fysom/)

```sh
pip install fysom
```

**Ulm-IQO/qudi-legacy** (173 stars)

[Ulm-IQO/qudi-legacy](https://github.com/Ulm-IQO/qudi-legacy) 

```python
@QtCore.Slot(str, str)
def stopModule(self, base, key):
    """ Figure out the module dependencies in terms of connections and deactivate module.

      @param str base: Module category
      @param str key: Unique module name

    """
    deps = self.getRecursiveModuleDependencies(base, key)
    sorteddeps = toposort(deps)
    if len(sorteddeps) == 0:
        sorteddeps.append(key)

    for mkey in reversed(sorteddeps):
        for mbase in ('hardware', 'logic', 'gui'):
            if mkey in self.tree['defined'][mbase] and mkey in self.tree['loaded'][mbase]:
                try:
                    deact = self.tree['loaded'][mbase][mkey].module_state.can('deactivate')
                except:
                    deact = True
                if deact:
                    logger.info('Deactivating module {0}.{1}'.format(mbase, mkey))
                    self.deactivateModule(mbase, mkey)
```

[core/manager.py](https://github.com/Ulm-IQO/qudi-legacy/blob/765180e1a6ef79ddcf8e548dfd3e0458a257cb5d/core/manager.py#L1181-L1203) · [More projects using fysom →](https://dashboard.exa.ai/playground/search?q=fysom%20GitHub%20projects)

**Quickstart**

```python
from fysom import Fysom
fsm = Fysom(initial='green', events=[('warn', 'green', 'yellow')])
fsm.warn()

```

From [README.rst](https://github.com/mriehl/fysom)

### Automaton

[GitHub](https://github.com/openstack/automaton) · [PyPI](https://pypi.org/project/automaton) · [Docs](https://pypi.org/project/automaton/)

Provides developer-friendly state machines for Python.

- Downloads / mo: 90.2K
- Stars: 62
- Last release: 3.5.0
- License: Apache-2.0
- Capabilities: [From the Automaton docs](https://pypi.org/project/automaton/)

**Strengths**

- **Separates events from reaction execution.** Drive events explicitly or use a runner for callback-driven transitions.
- **Supports hierarchical machines.** Compose nested finite machines for hierarchical state processing.

**Watch out for**

- **Frozen definitions reject additions.** Finish adding states, transitions, and reactions before freezing the machine.

```sh
pip install automaton
```

**openstack/taskflow** (376 stars)

[openstack/taskflow](https://github.com/openstack/taskflow) 

```python
def build(self, statistics, timeout=None, gather_statistics=True):
    """Builds a state-machine (that is used during running)."""
    if gather_statistics:
        watches = {}
        state_statistics = {}
        statistics['seconds_per_state'] = state_statistics
        watches = {}
        for timed_state in TIMED_STATES:
            state_statistics[timed_state.lower()] = 0.0
            watches[timed_state] = timeutils.StopWatch()
        statistics['discarded_failures'] = 0
        statistics['awaiting'] = 0
        statistics['completed'] = 0
        statistics['incomplete'] = 0

    memory = MachineMemory()
    if timeout is None:
        timeout = WAITING_TIMEOUT

    # Cache some local functions/methods...
    do_complete = self._completer.complete
    do_complete_failure = self._completer.complete_failure
    get_atom_intention = self._storage.get_atom_intention

    def do_schedule(next_nodes):
        with self._storage.lock.write_lock():
            return self._scheduler.schedule(
                sorted(
                    next_nodes,
                    key=lambda node: getattr(node, 'priority', 0),
                    reverse=True,
                )
            )

    def iter_next_atoms(atom=None, apply_deciders=True):
        # Yields and filters and tweaks the next atoms to run...
        maybe_atoms_it = self._selector.iter_next_atoms(atom=atom)
        for atom, late_decider in maybe_atoms_it:
            if apply_deciders:
                proceed = late_decider.check_and_affect(self._runtime)
                if proceed:
                    yield atom
            else:
                yield atom

    def resume(old_state, new_state, event):
        # This reaction function just updates the state machines memory
        # to include any nodes that need to be executed (from a previous
        # attempt, which may be empty if never ran before) and any nodes
        # that are now ready to be ran.
        with self._storage.lock.write_lock():
            memory.next_up.update(
                iter_utils.unique_seen(
                    (self._completer.resume(), iter_next_atoms())
                )
            )
        return SCHEDULE

    def game_over(old_state, new_state, event):
        # This reaction function is mainly a intermediary delegation
        # function that analyzes the current memory and transitions to
        # the appropriate handler that will deal with the memory values,
        # it is *always* called before the final state is entered.
        if memory.failures:
            return FAILED
        with self._storage.lock.read_lock():
            leftover_atoms = iter_utils.count(
                # Avoid activating the deciders, since at this point
                # the engine is finishing and there will be no more further
                # work done anyway...
                iter_next_atoms(apply_deciders=False)
            )
        if leftover_atoms:
            # Ok we didn't finish (either reverting or executing...) so
            # that means we must of been stopped at some point...
            LOG.trace(
                "Suspension determined to have been reacted to"
                " since (at least) %s atoms have been left in an"
                " unfinished state",
                leftover_atoms,
            )
            return SUSPENDED
        elif self._runtime.is_success():
            return SUCCESS
        else:
            return REVERTED

    def schedule(old_state, new_state, event):
        # This reaction function starts to schedule the memory's next
        # nodes (iff the engine is still runnable, which it may not be
        # if the user of this engine has requested the engine/storage
        # that holds this information to stop or suspend); handles failures
        # that occur during this process safely...
        with self._storage.lock.write_lock():
            current_flow_state = self._storage.get_flow_state()
            if current_flow_state == st.RUNNING and memory.next_up:
                not_done, failures = do_schedule(memory.next_up)
                if not_done:
                    memory.not_done.update(not_done)
                if failures:
                    memory.failures.extend(failures)
                memory.next_up.intersection_update(not_done)
            elif current_flow_state == st.SUSPENDING and memory.not_done:
                # Try to force anything not cancelled to now be cancelled
                # so that the executor that gets it does not continue to
                # try to work on it (if the future execution is still in
                # its backlog, if it's already being executed, this will
                # do nothing).
                memory.cancel_futures()
        return WAIT

    def complete_an_atom(fut):
        # This completes a single atom saving its result in
        # storage and preparing whatever predecessors or successors will
        # now be ready to execute (or revert or retry...); it also
        # handles failures that occur during this process safely...
        atom = fut.atom
        try:
            outcome, result = fut.result()
            do_complete(atom, outcome, result)
            if isinstance(result, failure.Failure):
                retain = do_complete_failure(atom, outcome, result)
                if retain:
                    memory.failures.append(result)
                else:
                    # NOTE(harlowja): avoid making any intention request
                    # to storage unless we are sure we are in DEBUG
                    # enabled logging (otherwise we will call this all
                    # the time even when DEBUG is not enabled, which
                    # would suck...)
                    if LOG.isEnabledFor(logging.DEBUG):
                        intention = get_atom_intention(atom.name)
                        LOG.debug(
                            "Discarding failure '%s' (in response"
                            " to outcome '%s') under completion"
                            " units request during completion of"
                            " atom '%s' (intention is to %s)",
                            result,
                            outcome,
                            atom,
                            intention,
                        )
                    if gather_statistics:
                        statistics['discarded_failures'] += 1
            if gather_statistics:
                statistics['completed'] += 1
        except futures.CancelledError:
            # Well it got cancelled, skip doing anything
            # and move on; at a further time it will be resumed
            # and something should be done with it to get it
            # going again.
            return WAS_CANCELLED
        except Exception:
            memory.failures.append(failure.Failure())
            LOG.exception("Engine '%s' atom post-completion failed", atom)
            return FAILED_COMPLETING
        else:
            return SUCCESSFULLY_COMPLETED

    def wait(old_state, new_state, event):
        # TODO(harlowja): maybe we should start doing 'yield from' this
        # call sometime in the future, or equivalent that will work in
        # py2 and py3.
        if memory.not_done:
            done, not_done = self._waiter(memory.not_done, timeout=timeout)
            memory.done.update(done)
            memory.not_done = not_done
        return ANALYZE

    def analyze(old_state, new_state, event):
        # This reaction function is responsible for analyzing all nodes
        # that have finished executing/reverting and figuring
        # out what nodes are now ready to be ran (and then triggering those
        # nodes to be scheduled in the future); handles failures that
        # occur during this process safely...
        next_up = set()
        with self._storage.lock.write_lock():
            while memory.done:
                fut = memory.done.pop()
                # Force it to be completed so that we can ensure that
                # before we iterate over any successors or predecessors
                # that we know it has been completed and saved and so on...
                completion_status = complete_an_atom(fut)
                if (
                    not memory.failures
                    and completion_status != WAS_CANCELLED
                ):
                    atom = fut.atom
                    try:
                        more_work = set(iter_next_atoms(atom=atom))
                    except Exception:
                        memory.failures.append(failure.Failure())
                        LOG.exception(
                            "Engine '%s' atom post-completion"
                            " next atom searching failed",
                            atom,
                        )
                    else:
                        next_up.update(more_work)
        current_flow_state = self._storage.get_flow_state()
        if (
            current_flow_state == st.RUNNING
            and next_up
            and not memory.failures
        ):
            memory.next_up.update(next_up)
            return SCHEDULE
        elif memory.not_done:
            if current_flow_state == st.SUSPENDING:
                memory.cancel_futures()
            return WAIT
        else:
            return FINISH

    def on_exit(old_state, event):
        LOG.trace(
            "Exiting old state '%s' in response to event '%s'",
            old_state,
            event,
        )
        if gather_statistics:
            if old_state in watches:
                w = watches[old_state]
                w.stop()
                state_statistics[old_state.lower()] += w.elapsed()
            if old_state in (st.SCHEDULING, st.WAITING):
                statistics['incomplete'] = len(memory.not_done)
            if old_state in (st.ANALYZING, st.SCHEDULING):
                statistics['awaiting'] = len(memory.next_up)

    def on_enter(new_state, event):
        LOG.trace(
            "Entering new state '%s' in response to event '%s'",
            new_state,
            event,
        )
        if gather_statistics and new_state in watches:
            watches[new_state].restart()

    state_kwargs = {
        'on_exit': on_exit,
        'on_enter': on_enter,
    }
    m = machines.FiniteMachine()
    m.add_state(GAME_OVER, **state_kwargs)
    m.add_state(UNDEFINED, **state_kwargs)
    m.add_state(st.ANALYZING, **state_kwargs)
    m.add_state(st.RESUMING, **state_kwargs)
    m.add_state(st.REVERTED, terminal=True, **state_kwargs)
    m.add_state(st.SCHEDULING, **state_kwargs)
    m.add_state(st.SUCCESS, terminal=True, **state_kwargs)
    m.add_state(st.SUSPENDED, terminal=True, **state_kwargs)
    m.add_state(st.WAITING, **state_kwargs)
    m.add_state(st.FAILURE, terminal=True, **state_kwargs)
    m.default_start_state = UNDEFINED

    m.add_transition(GAME_OVER, st.REVERTED, REVERTED)
    m.add_transition(GAME_OVER, st.SUCCESS, SUCCESS)
    m.add_transition(GAME_OVER, st.SUSPENDED, SUSPENDED)
    m.add_transition(GAME_OVER, st.FAILURE, FAILED)
    m.add_transition(UNDEFINED, st.RESUMING, START)
    m.add_transition(st.ANALYZING, GAME_OVER, FINISH)
    m.add_transition(st.ANALYZING, st.SCHEDULING, SCHEDULE)
    m.add_transition(st.ANALYZING, st.WAITING, WAIT)
    m.add_transition(st.RESUMING, st.SCHEDULING, SCHEDULE)
    m.add_transition(st.SCHEDULING, st.WAITING, WAIT)
    m.add_transition(st.WAITING, st.ANALYZING, ANALYZE)

    m.add_reaction(GAME_OVER, FINISH, game_over)
    m.add_reaction(st.ANALYZING, ANALYZE, analyze)
    m.add_reaction(st.RESUMING, START, resume)
    m.add_reaction(st.SCHEDULING, SCHEDULE, schedule)
    m.add_reaction(st.WAITING, WAIT, wait)

    m.freeze()
    return (m, memory)
```

[taskflow/engines/action_engine/builder.py](https://github.com/openstack/taskflow/blob/c485e402f117a07e8e75723e4d3d95c3f0fc371a/taskflow/engines/action_engine/builder.py#L119-L394) · [More projects using Automaton →](https://dashboard.exa.ai/playground/search?q=Public%20Python%20projects%20using%20automaton%20for%20workflow%20transitions%2C%20state%20guards%2C%20connection%20lifecycles%20and%20event-driven%20processing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from automaton.machines import FiniteMachine
machine = FiniteMachine()
machine.add_state('a')
machine.add_state('b')
machine.add_transition('a', 'b', 'advance')
machine.initialize(start_state='a')
machine.process_event('advance')

```

From [examples.rst](https://docs.openstack.org/automaton/latest/reference/index.html)

### Sismic

[GitHub](https://github.com/AlexandreDecan/sismic) · [PyPI](https://pypi.org/project/sismic) · [Docs](https://pypi.org/project/sismic/)

Interprets and checks statechart models.

- Downloads / mo: 6.6K
- Stars: 172
- Last release: 1.6.14
- License: LGPL-3.0
- Capabilities: [From the Sismic docs](https://pypi.org/project/sismic/)

```sh
pip install sismic
```

**Quickstart**

```python
from sismic.io import import_from_yaml
from sismic.interpreter import Interpreter

chart = import_from_yaml('''statechart:
  name: Example
  root state:
    name: root
    initial: idle
    states:
      - name: idle
''')
interpreter = Interpreter(chart)
interpreter.execute()

```

From [io.html](https://sismic.readthedocs.io/en/latest/api/io.html) · [Find projects using Sismic →](https://dashboard.exa.ai/playground/search?q=sismic%20GitHub%20projects)

## FAQ

### Which Python state machine library should I use?

[Python StateMachine](#python-statemachine) suits workflows with compound states, parallel regions, and async callbacks. [transitions](#transitions) suits object-oriented machines with hierarchy, asyncio, and diagram extensions. [Django FSM](#django-fsm) suits state fields on Django models.

### Which Python state machine libraries support asyncio?

[transitions](#transitions) provides asynchronous machine extensions. [Python StateMachine](#python-statemachine) selects its async engine automatically when async callbacks are registered.

### Can one machine instance be shared across threads?

[Python StateMachine](#python-statemachine) requires external synchronization for an instance shared across threads.

### Do diagram exports need extra dependencies?

Yes. Python StateMachine diagrams require pydot and the Graphviz tool. Automat image generation also requires Graphviz.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python state machine libraries transitions python-statemachine Automat automaton examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
