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
- The First Step: When you use
send(), the generator must already be "primed." We callnext(gen)first to move the execution to the firstyield. If you tried tosend()to a brand-new generator, Python would raise aTypeError(unless you sendNone). - The Assignment: In
increment = yield total, the code pauses at theyield. When you later executegen.send(10), the generator wakes up, treats theyieldstatement as if it evaluated to10, and assigns that10to the variableincrement. - The Loop Continues: The generator then processes the
ifstatement, updates thetotal, and loops back around to theyield, 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.