How to Send Values into a Python Generator Coroutine

Use the .send() method to pass values into a running generator coroutine and capture them.

Medium Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

21 lines
Python 3.9+
def 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

stdout
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

  1. Use `yield from` to delegate to a subgenerator
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.