How to Send Values into a Python Generator Coroutine
Use the .send() method to pass values into a running generator coroutine and capture them.
Python code
21 linesdef coroutine():
received = []
while True:
value = yield
received.append(value)
print(f"Coroutine received: {value}")
if value == "stop":
break
return received
if __name__ == "__main__":
gen = coroutine()
next(gen) # Prime the generator
gen.send("hello")
gen.send(42)
gen.send([1, 2, 3])
try:
gen.send("stop")
except StopIteration as e:
print(f"Coroutine finished. Received values: {e.value}")
Output
Coroutine received: hello
Coroutine received: 42
Coroutine received: [1, 2, 3]
Coroutine received: stop
Coroutine finished. Received values: ['hello', 42, [1, 2, 3]]
How it works
A generator becomes a coroutine when it contains a yield statement without an expression. Calling next(gen) primes the generator, moving execution to the first yield. Each gen.send(value) resumes the generator, assigns value to the yield expression, and continues until the next yield. When 'stop' is sent, the generator breaks out of the loop and returns a list, which is caught in the StopIteration exception's value attribute. This pattern allows two-way communication between the caller and the coroutine.
Common mistakes
- Forgetting to prime the generator with `next(gen)` before sending values
- Sending to a generator that hasn't started results in TypeError
- Not catching StopIteration when the generator exits cleanly
Variations
- Use `yield from` to delegate to a subgenerator
- Use `gen.close()` to terminate a generator without handling StopIteration
Real-world use cases
- Implementing a data stream processor that receives chunks and aggregates stats
- Building a state machine that transitions based on incoming events
- Creating a logging pipeline that accepts log entries and formats them in real time
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.