Skip to main content

A Queued State Machine Implementation for Python

Project description

qsm

A queued state machine implementation for Python.

A queued state machine is a small workflow runner where each state can schedule the next states to run. Instead of returning a single transition, states add state names to a queue. The machine dequeues one state at a time, executes it, and keeps going until the queue is empty.

Use append() for normal follow-up work. Use prepend() when a state needs to run before the work that is already waiting.

Installation

You can install this package with pip install qstate

Quickstart

from qsm import QSM, State, StateContext


class Start(State):
    def execute(self, ctx: StateContext) -> None:
        ctx.context["name"] = "World"
        ctx.queue.append("hello")
        ctx.queue.append("goodbye")


class Hello(State):
    def execute(self, ctx: StateContext) -> None:
        print(f"Hello {ctx.context['name']}!")


class Goodbye(State):
    def execute(self, ctx: StateContext) -> None:
        print(f"Goodbye {ctx.context['name']}!")


machine = QSM(initial_context={})
machine.state_map["initial_state"] = Start()
machine.state_map["hello"] = Hello()
machine.state_map["goodbye"] = Goodbye()
machine.loop()

Output:

Hello World!
Goodbye World!

The execution order is:

  1. start
  2. hello
  3. goodbye

JSON Configuration

You can also define a machine from JSON by pointing at importable context and state classes. Use QSM.from_json(data) for decoded dictionaries, QSM.from_json_text(text) for JSON strings, or QSM.from_config_file(path) for files.

See docs/config.md for the full config shape and examples.

Prepending Work

prepend() places a state at the front of the queue. This is useful for urgent or corrective work that should run before older queued states.

from qsm import State, StateContext


class Check(State):
    def execute(self, ctx: StateContext) -> None:
        if ctx.context["needs_login"]:
            ctx.queue.prepend("login")
        ctx.queue.append("continue")

If the queue already contains ["later"], this state can schedule login to run before later.

API

QSM

QSM(initial_context=None, initial_state="initial_state", max_queue_size=None)

QSM owns the state queue, the registered states, and shared workflow context.

  • machine.state_map maps state names to State instances.
  • machine.queue.append("state") schedules normal work.
  • machine.queue.prepend("state") schedules work at the front of the queue.
  • machine.get_next_state() dequeues the next state name and updates machine.current_state.
  • machine.execute_state("state") executes a registered state by name.
  • machine.execute_current_state() executes machine.current_state.
  • machine.loop() executes queued states until the queue is empty. It starts from a good state, it flushes the queue and enqueues the machine's initial state unless flush is False. Use flush=False to allow yourself to prime the queue prior to calling.

State

Create states by subclassing State and implementing execute().

from qsm import State, StateContext


class Example(State):
    def execute(self, ctx: StateContext):
        ...

execute() receives a StateContext with:

  • ctx.queue: the queue used to schedule more states.
  • ctx.context: the shared context object passed to QSM.

Notes

The queue stores state names as strings and is based on Python's queue.Queue locking model. It supports max-size blocking behavior, append(), and prepend().

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

qstate-1.1.1.tar.gz (141.1 kB view details)

Uploaded Source

Built Distribution

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

qstate-1.1.1-py3-none-any.whl (31.3 kB view details)

Uploaded Python 3

File details

Details for the file qstate-1.1.1.tar.gz.

File metadata

  • Download URL: qstate-1.1.1.tar.gz
  • Upload date:
  • Size: 141.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for qstate-1.1.1.tar.gz
Algorithm Hash digest
SHA256 e49798f4c00e73dece13bb6936d8211c534022b046689abdb8f11384e55cfb89
MD5 b3828ea95b6fedee2999855aaf11d2d7
BLAKE2b-256 445abc199dd9563f36396a0794482e181a85a01759b3023a3fbbb57e1c63a4af

See more details on using hashes here.

File details

Details for the file qstate-1.1.1-py3-none-any.whl.

File metadata

  • Download URL: qstate-1.1.1-py3-none-any.whl
  • Upload date:
  • Size: 31.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for qstate-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 05116fcbdca8f1273283e6237fc9b0b4e3b03316ac00938149dfbe372c6b1bdc
MD5 dde32922c08ea888774bbdde0b90c0bf
BLAKE2b-256 9f44dfb466aa32ca56e05a459ff8425a3fab49a84412611e669263fe7169c600

See more details on using hashes here.

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