Skip to main content

lightweight, context-driven finite state machine (FSM) library.

Project description

Ro FSM Library

A lightweight, context-driven finite state machine (FSM) library for Python that supports:

  • States with entry and exit actions.
  • Transitions with conditions based on a user-defined context.
  • Wildcard transitions for global state changes.
  • YAML-based configuration for declarative FSM definitions.
  • Safe evaluation of actions and conditions (only allowing context-based access).

Installation

pip install ro_fsm

Requires Python ≥3.8 and PyYAML for YAML parsing.

Overview

A state machine consists of:

  • States – Named entities with optional entry/exit actions.
  • Transitions – Connections between states, each with a boolean condition evaluated against a context object.
  • Context – User-defined object containing the data and methods that drive FSM logic.

Python API

State

Represents a single state in the FSM.

State(name: str, entry_action: Optional[Callable[[Any], None]] = None,
      exit_action: Optional[Callable[[Any], None]] = None)
  • name – Unique string identifier for the state.
  • entry_action – Function called when the state is entered (receives context).
  • exit_action – Function called when the state is exited (receives context).

Example:

idle = State(
    "Idle",
    entry_action=lambda ctx: print("Entering Idle"),
    exit_action=lambda ctx: print("Exiting Idle")
)

Transition

Encapsulates a transition to another state.

Transition(to_state: str, condition: Optional[Callable[[Any], bool]] = None)
  • to_state – Destination state name.
  • condition – Function returning a boolean; triggers transition if True.

StateMachine

Manages states, transitions, and context-driven updates.

StateMachine(initial_state: State, context: Any = None, s0_action_flag: bool = True)
  • initial_state – Starting state of the FSM.
  • context – Object passed to all actions and conditions.
  • s0_action_flag – Whether to run the entry action of the initial state immediately.

Methods

  • add_state(state: State) – Add a new state.
  • add_transition(from_state: str, to_state: str, condition: Callable[[Any], bool]) – Add a transition between states.
  • set_state(state_name: str, context: Any) – Force a state change.
  • update(context: Any = None) – Evaluate transitions and update the state.

YAML Constructor

StateMachine.from_yaml(path: str, context: Any, s0_action_flag: bool = True)
  • Loads states, transitions, and initial state from a YAML file.
  • Wildcard transitions (from: "*") have priority over state-specific transitions.

YAML Configuration

Define your FSM declaratively:

initial_state: Idle

states:
  - name: Idle
    entry_action: context.log("Idle state")
    exit_action: context.cleanup()
    transitions:
      - to: Active
        condition: context.ready()

  - name: Active
    entry_action: context.start()
    transitions:
      - to: Finished
        condition: context.done()

  - name: Finished

# Wildcard transitions apply globally
transitions:
  - from: "*"
    to: OutOfOrder
    condition: context.error

Rules:

  1. States cannot be named "*".
  2. Actions and conditions must only reference context.
  3. Top-level transitions (wildcards) override state-specific transitions.
  4. Expression evaluation is sandboxed via AST parsing to prevent unsafe code execution.

Example Usage

from fsm import StateMachine
from context import Context  # user-defined context class

ctx = Context()
sm = StateMachine.from_yaml("vending_machine.yaml", ctx)

# Initial state
print(sm.current_state.name)

# Step through FSM
while sm.current_state.name != "Finished":
    sm.update(ctx)

Best Practices

  • Keep actions and conditions pure: avoid side effects outside the context object.
  • Use wildcard transitions for emergency/error handling.
  • Validate YAML using schema tools to prevent misconfigurations.
  • Use entry_action and exit_action for logging, resource management, or triggering side effects.

Safety & Security

  • Conditions and actions are evaluated in a sandbox.
  • Only context and its attributes/methods can be accessed in YAML expressions.
  • AST parsing prevents arbitrary code execution.

License

MIT License.

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

ro_fsm-0.7.0.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

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

ro_fsm-0.7.0-py3-none-any.whl (7.0 kB view details)

Uploaded Python 3

File details

Details for the file ro_fsm-0.7.0.tar.gz.

File metadata

  • Download URL: ro_fsm-0.7.0.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.17

File hashes

Hashes for ro_fsm-0.7.0.tar.gz
Algorithm Hash digest
SHA256 d09cbf3ec3675d37d890921e5015393c4dc4b6b543c6c23a46964da663ab881b
MD5 d49160344a7e430f104133ca0c638fc6
BLAKE2b-256 464ced793a5bfa5f7bd648b468dbe80d6d4468a1835a00e28dd719fa8acdde7f

See more details on using hashes here.

File details

Details for the file ro_fsm-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: ro_fsm-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 7.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.17

File hashes

Hashes for ro_fsm-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 304ff9b6bc9d04b725256674205983d45d32d951d632fed70056816be1207c63
MD5 32042811151bd600a9b5f9ad799f3b4b
BLAKE2b-256 9c92533868ae829af14e03dc29b59198dde2bdc2cb38b0064dbfdb96d5116342

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