In this lesson, you will learn how to turn a standard generator into a two-way communication channel by using the .send() method to inject data back into a running process.
Moving Beyond One-Way Streams
Up until now, our generators have been "producers"—they simply yield values to us, one by one. However, a coroutine is a specialized generator that can also act as a "consumer." By using the .send() method instead of just next(), you can pause execution, pass a value into the generator, and let the generator resume while using that value as the result of its yield expression.
Bidirectional Data Flow
To receive a value, you assign the yield statement to a variable inside your generator function. Here is how it looks in practice:
def echo_coroutine():
print("Coroutine started!")
while True:
# The generator pauses here, waiting for a value
received = yield
print(f"Coroutine received: {received}")
# Initialize the coroutine
coro = echo_coroutine()
# Prime the generator (required before sending data)
next(coro)
# Now send values into it
coro.send("Hello!")
coro.send("World!")
How it Works
- Priming: When you first create a generator object, it isn't "active" yet. You must call
next()(orsend(None)) to move execution to the firstyieldstatement so the generator is ready to receive input. - The Injection: When you call
coro.send("Hello!"), theyieldexpression inside the function evaluates to the string"Hello!". The variablereceivedcaptures this value, and the generator continues until it hits the nextyield. - Control: This creates a powerful loop where the main program and the generator take turns controlling the execution flow, effectively allowing you to pass state back and forth dynamically.
This pattern is the foundation for creating sophisticated data processing pipelines where components can react to incoming data rather than just passively streaming it.
Key Takeaway: The .send() method transforms a generator into a coroutine by allowing the yield keyword to act as an expression that captures injected values, enabling bidirectional communication between your code and the generator.