AtsushiSakai/PythonRobotics · error · ValueError

State machine is not initialized

Error message

State machine is not initialized

What it means

Raised by StateMachine.process when self._state is None, i.e. the machine was never given an initial state. Processing an event requires a current state to look up transitions.

Source

Thrown at MissionPlanning/StateMachine/state_machine.py:236

        if isinstance(state, str):
            self._state = self._get_state(state)
        else:
            self._state = state

    def get_current_state(self):
        return self._state

    def process(self, event: str) -> None:
        """Process an event in the state machine.

        Args:
            event: Event name.

        Example:
            >>> machine.process("start")
        """
        if self._state is None:
            raise ValueError("State machine is not initialized")

        if self._has_event(event):
            self.state_transition(self._state, event)
        else:
            raise ValueError(f"Invalid event: {event}")

    def generate_plantuml(self) -> str:
        """Generate PlantUML state diagram representation of the state machine.

        Returns:
            str: PlantUML state diagram code.
        """
        if self._state is None:
            raise ValueError("State machine is not initialized")

        plant_uml = ["@startuml"]
        plant_uml.append("[*] --> " + self._state.name)

View on GitHub (pinned to 1fe4fb980f)

Solutions

  1. Set the initial state before processing events (call the machine's init/start API that assigns _state).
  2. Verify initialization succeeded (assert machine._state is not None or a public accessor).
  3. Move event subscriptions/loops to start only after machine setup completes.

Example fix

# before
machine = StateMachine('m')
machine.process('start')

# after
machine = StateMachine('m')
machine.set_initial_state(idle_state)  # or machine.initialize()
machine.process('start')
Defensive patterns

Strategy: validation

Validate before calling

assert machine._state is not None, 'initialize the state machine before processing events'

Type guard

def is_initialized(machine) -> bool:
    return machine._state is not None

Try / catch

try:
    machine.process(event)
except ValueError as e:
    if 'not initialized' in str(e):
        machine.initialize(); machine.process(event)
    else:
        raise

Prevention

When it happens

Trigger: Creating a StateMachine, not setting the initial state (no initial_state/start call), then calling process('...') immediately.

Common situations: Forgetting the initialization step in setup code, or initialization failing silently earlier (e.g. exception during state setup) leaving _state unset.

Related errors


AI-assisted analysis of AtsushiSakai/PythonRobotics@1fe4fb980f (2026-08-28). Data as JSON: /api/errors/4318942a4640cb96. Report an issue: GitHub.