Course contentsShow
← Python
Lesson 310 of 1,0605. Advanced Iteration and ComprehensionsFree lesson

Implementing Coroutines with the Send Method

You will enable bidirectional communication in your generators by using the send method to pass data into a running process.

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

  1. Priming: When you first create a generator object, it isn't "active" yet. You must call next() (or send(None)) to move execution to the first yield statement so the generator is ready to receive input.
  2. The Injection: When you call coro.send("Hello!"), the yield expression inside the function evaluates to the string "Hello!". The variable received captures this value, and the generator continues until it hits the next yield.
  3. 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.