In this lesson, you will learn how to build robust, event-driven state machines that encapsulate logic and internal state using Python generator functions.
Moving Beyond Simple Iteration
Up until now, you have used generators primarily to yield values or handle streams of data. However, because a generator function "pauses" its execution and remembers its local variables, it acts as a perfect vessel for a state machine.
A state machine is a system that exists in one of several defined "states" and transitions between them based on inputs. By using a while True loop combined with the .send() method, you can create a generator that waits for input, updates its internal state, and produces a result based on that state.
The "Traffic Light" Controller
Consider a simplified traffic light that transitions between states based on signals sent to it:
def traffic_light():
state = "RED"
while True:
command = yield state
if command == "next":
if state == "RED":
state = "GREEN"
elif state == "GREEN":
state = "YELLOW"
elif state == "YELLOW":
state = "RED"
# Initialize the state machine
light = traffic_light()
next(light) # Prime the generator
print(light.send("next")) # Outputs: GREEN
print(light.send("next")) # Outputs: YELLOW
print(light.send("next")) # Outputs: RED
Why Use Generators for States?
In this pattern, the state variable persists across calls to send(). Unlike a class-based implementation, you don't need to manage self references or complex boilerplate code. The generator maintains the "current" state in its local namespace, and the yield statement serves as both the output of the current state and the injection point for the next input.
This approach is highly memory-efficient and keeps your state transitions isolated from the rest of your application. You can chain these state machines or wrap them in pipelines to handle complex, asynchronous logic without cluttering your global scope with persistent variables.
Key Takeaway: Generator functions allow you to define self-contained state machines that persist their internal logic between execution pauses, providing a clean, memory-efficient way to handle sequential state transitions.