Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

can you show me how to structure a python class with a statemachine inside? I'm…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-3.3-70b-instruct’s answer.
  1. 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

  2. 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.BOOTING
    

    Quick 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 ───────────────────

    1. Enumerate STATES
      • Use Enum for clarity & type-safety.
      • Add docstrings / comments if the meaning isn’t obvious.

    2. 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.

    3. Draft a transition table (whiteboard helps)

    CurrentEventNext
    OFFpower_onBOOTING
    BOOTINGboot_successON
    ………
    1. Create a “dispatcher”
      state -> handler dict so you don’t need nested if/elif all over.

    2. Write pure STATE HANDLER functions
      • Given (event, context) → returns next-state (or None to stay).
      • Avoid side-effects inside handlers; keep them readable.

    3. Centralise the transition logic
      _transition_to() is the only place that mutates self.state.
      Hook in optional _on_enter / _on_exit to keep lifecycle code tidy.

    4. Expose a small public contract
      on_event(e) is the single entry.
      If you also need timed ticks or external inspectors, add separate methods.

    5. (Optional) bring in extra goodies
      • Context data: add a .data attribute or use a dedicated dataclass.
      • Guard conditions: just add extra if … inside handlers.
      • Async / threads: make on_event async def or queue events.

    Why not use a library? • For simple flows the above is enough.
    • For big graphs consider transitions, automaton, or asyncio’s FSM flavour.

    ─────────────────── Gotchas & Tips ─────────────────── • Never mutate self.state outside 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 🚀

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.