Asyncio Event Driven State Machine

Build an event-driven state machine with asyncio for protocol parsing and workflow orchestration.

PythonData Fetching

Code

pythonsnippet
21 lines
import asyncio
from enum import Enum, auto

class State(Enum):
    IDLE = auto()
    PROCESSING = auto()
    DONE = auto()

class StateMachine:
    def __init__(self):
        self.state = State.IDLE
        self.queue = asyncio.Queue()
    async def run(self):
        while self.state != State.DONE:
            event = await self.queue.get()
            await self.handle(event)
    async def handle(self, event):
        if self.state == State.IDLE and event == 'start':
            self.state = State.PROCESSING
        elif self.state == State.PROCESSING and event == 'finish':
            self.state = State.DONE

What the code does

Count the classes State and StateMachine and the functions __init__, run and handle as the entire surface area of Asyncio Event Driven State Machine.

Iteration happens inside while self.state != State.DONE — everything outside it runs once. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. From asyncio it pulls Enum, auto — the imports name exactly which library surface the snippet touches.

Watch out for

  • Requires asyncio as a package; the snippet will not run without it.

Using it

Entry signature: def run(self)

run is the public entry point; everything else in the file exists to support it.

Key statements

elif self.state == State.PROCESSING and event == 'finish':
    self.state = State.DONE
async def run(self):
    while self.state != State.DONE:
        event = await self.queue.get()
        await self.handle(event)
def __init__(self):
    self.state = State.IDLE
    self.queue = asyncio.Queue()

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`asyncio` — install it with the package manager before running.