Python Coroutine send() Error Fix
In this tutorial, you'll learn about Python Coroutine send() Error Fix. We cover key concepts, practical examples, and best practices.
Python's send() method sends a value into a generator or coroutine that has been paused at a yield expression. Common errors occur when sending before the first yield or sending to a non-generator coroutine.
The Wrong Way
def accumulator():
total = 0
while True:
value = yield total
total += value
gen = accumulator()
result = gen.send(10)
Output:
Traceback (most recent call last):
File "script.py", line 8, in <module>
result = gen.send(10)
TypeError: can't send non-None value to a just-started generator
The Right Way
Prime the generator with next() or send(None) before sending values:
def accumulator():
total = 0
while True:
value = yield total
total += value
gen = accumulator()
next(gen) # Prime the generator
result = gen.send(10)
print(f"After sending 10: {result}")
result = gen.send(5)
print(f"After sending 5: {result}")
Output:
After sending 10: 10
After sending 5: 15
Step-by-Step Fix
1. Always prime before sending
gen = my_coroutine()
next(gen) # Advance to first yield
gen.send("value") # Now it works
2. Use a priming decorator
def coroutine(func):
def primer(*args, **kwargs):
gen = func(*args, **kwargs)
next(gen)
return gen
return primer
@coroutine
def printer():
while True:
msg = yield
print(f"Received: {msg}")
p = printer()
p.send("Hello") # No need to prime manually
p.send("World")
Output:
Received: Hello
Received: World
3. Use async/await for modern coroutines
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return "data"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
4. Yield from for sub-generators
def sub_gen():
received = yield
print(f"Sub received: {received}")
def main_gen():
yield from sub_gen()
gen = main_gen()
next(gen)
gen.send("hello")
Output:
Sub received: hello
Prevention Tips
- Prime generators with
next(gen)before usingsend(). - Use a decorator to auto-prime coroutine generators.
- Prefer
async defwithawaitfor new code instead of generator-based coroutines. - Always handle
StopIterationwhen iterating generators. - Document whether a generator expects values via
send()or standard iteration.
Common Mistakes with coroutine send
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro