can you show me how to structure a python class with a statemachine inside? I'm…
- User
can you show me how to structure a python class with a statemachine inside? I'm especially interested in the state handling mechanism, and steps
- Assistant
Below is a minimal, but idiomatic, pattern you can copy-paste and grow into a full-blown state-machine.
It shows• how to define the states & events
• how the “dispatcher” picks the right state-handler
• how to do clean transitions (+ optional enter / exit hooks)After the code you’ll find a step-by-step recipe so you can adapt the pattern to your own problem domain.
from enum import Enum, auto from typing import Callable, Dict, Optional class DeviceState(Enum): OFF = auto() BOOTING = auto() ON = auto() ERROR = auto() class Device: """A tiny embedded‐style device with an internal state-machine.""" # ────────────────────────────────────────────────────────── # 1) Construction ───────────────────────────────────────── # ────────────────────────────────────────────────────────── def __init__(self) -> None: self.state: DeviceState = DeviceState.OFF self._handlers: Dict[DeviceState, Callable[[str], Optional[DeviceState]]] = { DeviceState.OFF: self._handle_off, DeviceState.BOOTING: self._handle_booting, DeviceState.ON: self._handle_on, DeviceState.ERROR: self._handle_error, } # ────────────────────────────────────────────────────────── # 2) Public API ────────────────────────────────────────── # ────────────────────────────────────────────────────────── def on_event(self, event: str) -> None: """ External front-door. Feed events into the machine. """ print(f"[event] {event}") # pick correct handler based on *current* state handler = self._handlers[self.state] next_state = handler(event) if next_state is not None and next_state != self.state: self._transition_to(next_state) # ────────────────────────────────────────────────────────── # 3) Transition glue (optional enter/exit hooks) ────────── # ────────────────────────────────────────────────────────── def _transition_to(self, new_state: DeviceState) -> None: self._on_exit(self.state) print(f"[transition] {self.state.name} → {new_state.name}") self.state = new_state self._on_enter(self.state) def _on_enter(self, state: DeviceState) -> None: if state is DeviceState.BOOTING: print("Spinning up firmware …") elif state is DeviceState.ON: print("Device is live! ✅") elif state is DeviceState.ERROR: print("!! ERROR MODE !!") # etc. def _on_exit(self, state: DeviceState) -> None: if state is DeviceState.ON: print("Shutting down gracefully …") # etc. # ────────────────────────────────────────────────────────── # 4) STATE HANDLERS (pure functions) ──────────────────── # ────────────────────────────────────────────────────────── # Each returns the *next* state (or None to stay put) def _handle_off(self, event: str) -> Optional[DeviceState]: if event == "power_on": return DeviceState.BOOTING def _handle_booting(self, event: str) -> Optional[DeviceState]: if event == "boot_success": return DeviceState.ON elif event == "error": return DeviceState.ERROR def _handle_on(self, event: str) -> Optional[DeviceState]: if event == "power_off": return DeviceState.OFF elif event == "error": return DeviceState.ERROR def _handle_error(self, event: str) -> Optional[DeviceState]: if event == "reset": return DeviceState.BOOTINGQuick demo
dev = Device() dev.on_event("power_on") dev.on_event("boot_success") dev.on_event("error") dev.on_event("reset") dev.on_event("boot_success") dev.on_event("power_off")Output
[event] power_on [transition] OFF → BOOTING Spinning up firmware … [event] boot_success [transition] BOOTING → ON Device is live! ✅ [event] error !! ERROR MODE !! [transition] ON → ERROR [event] reset [transition] ERROR → BOOTING Spinning up firmware … [event] boot_success [transition] BOOTING → ON Device is live! ✅ [event] power_off Shutting down gracefully … [transition] ON → OFF─────────────────── Step-by-Step Recipe ───────────────────
-
Enumerate STATES
• UseEnumfor clarity & type-safety.
• Add docstrings / comments if the meaning isn’t obvious. -
List EVENTS (a.k.a. “triggers”)
• Could be strings, other Enums, or even rich objects carrying data.
• Rule of thumb: all stimuli that can change behaviour deserve a name. -
Draft a transition table (whiteboard helps)
Current Event Next OFF power_on BOOTING BOOTING boot_success ON … … … -
Create a “dispatcher”
state -> handlerdict so you don’t need nested if/elif all over. -
Write pure STATE HANDLER functions
• Given (event, context) → returns next-state (or None to stay).
• Avoid side-effects inside handlers; keep them readable. -
Centralise the transition logic
_transition_to()is the only place that mutatesself.state.
Hook in optional_on_enter/_on_exitto keep lifecycle code tidy. -
Expose a small public contract
on_event(e)is the single entry.
If you also need timed ticks or external inspectors, add separate methods. -
(Optional) bring in extra goodies
• Context data: add a.dataattribute or use a dedicated dataclass.
• Guard conditions: just add extraif …inside handlers.
• Async / threads: makeon_eventasync defor queue events.
Why not use a library? • For simple flows the above is enough.
• For big graphs considertransitions,automaton, orasyncio’s FSM flavour.─────────────────── Gotchas & Tips ─────────────────── • Never mutate
self.stateoutside the transition helper.
• Keep handlers tiny—complexity explodes if they grow.
• Unit-test transition matrix: parametrize (state, event, expected_state).
• Consider a DEBUG flag printing the[event],[transition]logs you saw.That’s it—drop this skeleton into your project, swap in your own states/events, and you have a clean, maintainable in-class state machine 🚀
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.