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

Injecting Values into Generators with Send

Use the send method to pass data into a running generator, enabling bidirectional communication between the caller and the stream.

In this lesson, you will learn how to turn a standard one-way generator into a two-way communication channel using the send() method.

Beyond One-Way Traffic

Up until now, you have used next() to pull values out of a generator. The generator "yielded" a value and then paused, waiting for you to ask again. But what if you wanted to pass information back into that paused generator to influence what it does next?

The send() method allows you to do exactly that. When you call generator.send(value), the value you provide is received by the generator as the result of the yield expression it was previously stuck on.

A Concrete Example

Consider a simple generator that tracks a running total but allows you to reset or modify that total from the outside:

def accumulator():
    total = 0
    while True:
        # The yield statement acts as a receiver
        increment = yield total
        if increment is not None:
            total += increment

gen = accumulator()

# Initialize the generator
print(next(gen))        # Output: 0

# Send values in
print(gen.send(10))     # Output: 10
print(gen.send(5))      # Output: 15

How It Works

  1. The First Step: When you use send(), the generator must already be "primed." We call next(gen) first to move the execution to the first yield. If you tried to send() to a brand-new generator, Python would raise a TypeError (unless you send None).
  2. The Assignment: In increment = yield total, the code pauses at the yield. When you later execute gen.send(10), the generator wakes up, treats the yield statement as if it evaluated to 10, and assigns that 10 to the variable increment.
  3. The Loop Continues: The generator then processes the if statement, updates the total, and loops back around to the yield, where it pauses again, waiting for your next instruction.

This pattern transforms generators from simple data producers into dynamic, interactive state machines.

Key Takeaway: The send() method allows you to pass data into a generator by treating the yield statement as an expression that captures the sent value, enabling real-time bidirectional communication.