Skip to main content

Lightweight, decorator-based implementation of a Finite State Machine

Project description

Finite State Machine

Build Status License: MIT Code Style: Black

Lightweight, decorator-based Python implementation of a Finite State Machine.

Installation

pip install finite-state-machine

Usage

You will need to subclass StateMachine and set the state instance variable.

The transition decorator can be used to specify valid transitions.

See examples for sample State Machine workflows.

Example

from finite_state_machine import StateMachine, transition

class Turnstile(StateMachine):
    initial_state = "close"

    def __init__(self):
        self.state = self.initial_state
        super().__init__()

    @transition(source=["close", "open"], target="open")
    def insert_coin(self):
        pass

    @transition(source="open", target="close")
    def pass_thru(self):
        pass

REPL

In [2]: turnstile = Turnstile()

In [3]: turnstile.state
Out[3]: 'close'

In [4]: turnstile.insert_coin()

In [5]: turnstile.state
Out[5]: 'open'

In [6]: turnstile.insert_coin()

In [7]: turnstile.state
Out[7]: 'open'

In [8]: turnstile.pass_thru()

In [9]: turnstile.state
Out[9]: 'close'

In [10]: turnstile.pass_thru()
---------------------------------------------------------------------------
InvalidStartState                         Traceback (most recent call last)
<ipython-input-10-6abc6f4be1cd> in <module>
----> 1 turnstile.pass_thru()

~/state_machine.py in _wrapper(*args, **kwargs)
     32
     33             if self.state not in source:
---> 34                 raise InvalidStartState
     35
     36             for condition in conditions:

InvalidStartState:

Contributing

  1. Clone repo
  2. Create a virtual environment
  3. pip install -r requirements_dev.txt
  4. Install pre-commit
  5. Set up pre-commit hooks in repo: pre-commit install

Running Tests

pytest

Release

Use SemVer for versioning strategy

Instructions

  1. Grab last version, X.Y.Z
  2. Generate changelog: python scripts/generate_changelog.py -v X.Y.Z
  3. Cut a release on GitHub
  4. Upload to PyPI with flit

Flit Workflow

pip install flit
flit build --format sdist
flit publish --repository testpypi

Inspiration

This project is inspired by django-fsm. Wanted a decorator-based state machine without having to use Django.

Project details


Download files

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

Source Distribution

finite-state-machine-0.2.0.tar.gz (6.1 kB view hashes)

Uploaded Source

Built Distribution

finite_state_machine-0.2.0-py3-none-any.whl (3.5 kB view hashes)

Uploaded Python 3

Supported by

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