Finite State Machine in Python (4 Examples)

A finite state machine in Python is a set of states, plus rules saying which event moves you from one state to the next. The simplest version is an Enum for the states and a dictionary of transitions:

TRANSITIONS = {(State.PENDING, "pay"): State.PAID, ...}
state = TRANSITIONS[(state, event)]

Each of these state machines ran on Python 3.12.5, using an online store’s order workflow as the main example.

We’ll build a transition table, wrap it in a class that blocks invalid moves, write a traffic light with match, and use a state machine to validate ZIP codes.

What is a finite state machine?

  • States: a fixed list of situations, like pending, paid and shipped.
  • Events: things that happen, like pay or ship.
  • Transitions: rules mapping (state, event) to the next state.
  • Start and final states: where it begins, and where it’s allowed to stop.

You can be in only one state at a time. That one rule removes a whole class of bugs, like an order that’s somehow both cancelled and shipped.

Finite state machine in Python with a transition table

I like starting with a dictionary keyed by (state, event). The whole machine fits on one screen, so it’s easy to check against the business rules:

from enum import Enum, auto

class State(Enum):
    PENDING = auto()
    PAID = auto()
    SHIPPED = auto()
    DELIVERED = auto()
    CANCELLED = auto()

# (current state, event) -> next state
TRANSITIONS = {
    (State.PENDING, "pay"): State.PAID,
    (State.PENDING, "cancel"): State.CANCELLED,
    (State.PAID, "ship"): State.SHIPPED,
    (State.PAID, "cancel"): State.CANCELLED,
    (State.SHIPPED, "deliver"): State.DELIVERED,
}

state = State.PENDING
for event in ["pay", "ship", "deliver"]:
    state = TRANSITIONS[(state, event)]
    print(f"{event:<8} -> {state.name}")

Output:

pay      -> PAID
ship     -> SHIPPED
deliver  -> DELIVERED
Command Prompt output of a Python finite state machine moving an order from PENDING to PAID, SHIPPED and DELIVERED
Three events, three transitions, and the order ends up delivered.

auto() numbers the Enum members for you. An event that isn’t in the table raises KeyError, which the class version turns into a clearer message. More on Enums alongside constants in Python.

A state machine class that rejects invalid transitions

In real code you’ll want the state attached to an object, a readable error for bad events, and a history. Here’s an order class that does all three:

from enum import Enum

class OrderState(Enum):
    PENDING = "pending"
    PAID = "paid"
    SHIPPED = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"

class Order:
    ALLOWED = {
        OrderState.PENDING: {"pay": OrderState.PAID, "cancel": OrderState.CANCELLED},
        OrderState.PAID: {"ship": OrderState.SHIPPED, "cancel": OrderState.CANCELLED},
        OrderState.SHIPPED: {"deliver": OrderState.DELIVERED},
    }

    def __init__(self, number, total):
        self.number, self.total = number, total
        self.state = OrderState.PENDING
        self.history = [self.state.value]

    def trigger(self, event):
        options = self.ALLOWED.get(self.state, {})
        if event not in options:
            raise ValueError(f"can't '{event}' an order that is {self.state.value}")
        self.state = options[event]
        self.history.append(self.state.value)

order = Order("A-2026-1121", 89.99)
order.trigger("pay")
order.trigger("ship")
try:
    order.trigger("cancel")              # too late: it already shipped
except ValueError as err:
    print("ValueError:", err)
order.trigger("deliver")
print(order.number, f"${order.total:.2f}", " -> ".join(order.history))

Output:

ValueError: can't 'cancel' an order that is shipped
A-2026-1121 $89.99 pending -> paid -> shipped -> delivered
Command Prompt output of a Python state machine class rejecting a cancel after shipping and printing the order history
Cancelling a shipped order is refused, and the history shows every state it passed through.

Keeping the allowed moves in one class-level dictionary means the rules live in one place, not scattered across if statements.

Can you build a state machine with match/case?

Yes. For small machines, a function with match reads like a description of the states. Each case returns the next state and how long to stay there:

import time

def next_light(light):
    match light:
        case "green":
            return "yellow", 3
        case "yellow":
            return "red", 2
        case "red":
            return "green", 4
    raise ValueError(light)

light, elapsed = "red", 0
for _ in range(6):
    light, seconds = next_light(light)
    elapsed += seconds
    print(f"t={elapsed:>2}s  {light:<6} for {seconds}s")
    time.sleep(0.1)                      # shortened so the demo runs quickly

Output:

t= 4s  green  for 4s
t= 7s  yellow for 3s
t= 9s  red    for 2s
t=13s  green  for 4s
t=16s  yellow for 3s
t=18s  red    for 2s
Command Prompt output of a Python traffic light state machine cycling green, yellow and red using match case
Starting from red, the light cycles green, yellow and red twice, with a running clock.

match needs Python 3.10 or newer. For the older if/elif style, see if else in Python.

Use a state machine to parse text

State machines are how many parsers and regular expressions work under the hood. This one reads a ZIP code one character at a time and accepts only 12345 or 12345-6789:

def is_zip(text):
    """FSM that accepts 12345 or 12345-6789."""
    state, count = "FIRST5", 0
    for ch in text:
        if state == "FIRST5" and ch.isdigit():
            count += 1
            if count == 5:
                state = "GOT5"
        elif state == "GOT5" and ch == "-":
            state, count = "LAST4", 0
        elif state == "LAST4" and ch.isdigit():
            count += 1
            if count == 4:
                state = "GOT9"
        else:
            return False, f"stuck in {state} at {ch!r}"
    return state in ("GOT5", "GOT9"), f"ended in {state}"

for code in ["78701", "10001-1234", "9021", "60614-12", "33101x"]:
    ok, why = is_zip(code)
    print(f"{code:<11} {'valid' if ok else 'invalid':<8} ({why})")

Output:

78701       valid    (ended in GOT5)
10001-1234  valid    (ended in GOT9)
9021        invalid  (ended in FIRST5)
60614-12    invalid  (ended in LAST4)
33101x      invalid  (stuck in GOT5 at 'x')
Command Prompt output of a Python finite state machine validating US ZIP and ZIP+4 codes and explaining failures
Each failure says which state it was in, which makes debugging easy.

In practice, re.fullmatch(r"\d{5}(-\d{4})?", code) does the same job. A regex compiles to a similar machine; see Python re.sub for more regex.

Which state machine approach should you use?

ApproachGood for
Transition dictionaryClear rules, easy to print or test
Class with allowed movesObjects with history and validation
match functionSmall machines with simple logic per state
Character-level FSMParsers and input validation
A library like transitionsLarge machines with callbacks and diagrams

Here are more Python design guides worth reading next:

Frequently asked questions

What is a finite state machine in Python?

A model with a fixed set of states and rules for moving between them on events, usually built with an Enum and a transition dictionary.

How do I prevent invalid transitions?

Store the allowed (state, event) pairs and raise an error when an event isn’t allowed in the current state.

Should I use Enum for states?

Yes. Enums prevent typos and make states easy to compare and print.

Is there a Python library for state machines?

Yes. The third-party transitions library adds callbacks, conditions and diagrams for bigger machines.

Where are state machines used?

Order workflows, games, network protocols, UI screens, traffic lights and text parsers.

Where is Enum documented?

See enum in the Python docs.