A coroutine is a suspendable computation that can pause and resume, letting independently structured tasks share execution cooperatively without running in parallel. Unlike a regular function, it does not need to run from start to finish before another task proceeds. section 2.0 section 2.2
Core mechanics:
- Calling a coroutine can return a controllable generator object instead of executing the body immediately. section 2.2
- Each yield pauses execution and preserves the coroutine's state; a later next() resumes from that point. section 2.2
- Coroutines run within a single thread, providing concurrency without parallelism or additional threads. section 2.1.2 section 2.5
A resumable generator
A coroutine yielding "foo" and then "bar" returns the first value on the first next(coro) call, pauses, and returns the second on the next call. After the final yield, execution reaches return "end" and signals completion through StopIteration, whose value contains "end". section 2.2
def coroutine():
yield "foo"
yield "bar"
return "end"
coro = coroutine()
while True:
try:
print(next(coro)) # "foo" then "bar"
except StopIteration as e:
print(e.value) # "end"
break
Use the listing to trace initialization, successive resumptions, yielded values, and final completion. section 2.2








