BehavioralPythonverifiedVerified

State Pattern in Python

Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

How to Implement the State Pattern in Python

1Step 1: Define the state interface using Protocol

from typing import Protocol, Literal

TrafficLightColor = Literal["red", "green", "yellow"]


class TrafficLightState(Protocol):
    @property
    def color(self) -> TrafficLightColor: ...
    def next_state(self) -> "TrafficLightState": ...
    def can_go(self) -> bool: ...

2Step 2: Implement concrete state classes

class RedLight:
    @property
    def color(self) -> TrafficLightColor:
        return "red"

    def next_state(self) -> TrafficLightState:
        return GreenLight()

    def can_go(self) -> bool:
        return False


class GreenLight:
    @property
    def color(self) -> TrafficLightColor:
        return "green"

    def next_state(self) -> TrafficLightState:
        return YellowLight()

    def can_go(self) -> bool:
        return True


class YellowLight:
    @property
    def color(self) -> TrafficLightColor:
        return "yellow"

    def next_state(self) -> TrafficLightState:
        return RedLight()

    def can_go(self) -> bool:
        return False

3Step 3: Create the context that delegates to states

class TrafficLight:
    def __init__(self) -> None:
        self._state: TrafficLightState = RedLight()

    def advance(self) -> None:
        self._state = self._state.next_state()

    @property
    def color(self) -> TrafficLightColor:
        return self._state.color

    def can_go(self) -> bool:
        return self._state.can_go()

4Step 4: Cycle through states and observe transitions

light = TrafficLight()
print(light.color, light.can_go())  # red False
light.advance()
print(light.color, light.can_go())  # green True
light.advance()
print(light.color, light.can_go())  # yellow False
light.advance()
print(light.color, light.can_go())  # red False

State Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

State Pattern in the Real World

Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.