Skip to the solution
HardDSA13 min read

What is the difference between a generator and a coroutine?

546 views

The problem

Question presented to candidate: "Generators and coroutines both pause and resume, and they even share methods like send(). So what really is the difference between a generator and a coroutine in Python, and why can you not just await a generator?"

What a strong answer should cover:

  • Purpose: a generator (def + yield) produces a sequence of values for its caller; a native coroutine (async def) waits for results and is driven by an event loop.
  • Who drives it: a generator is pulled with next() / for; a coroutine is resumed with send(None) by an event loop and is not an iterator (next(coro) is a TypeError).
  • The shared machinery: both are suspended frames with send / throw / close, both report their return value through StopIteration.value; the code-object flags differ (GENERATOR vs COROUTINE), and inspect can tell them apart.
  • Awaitability: only coroutines, Futures/Tasks, objects with __await__, and types.coroutine-decorated generators can be awaited; await on a bare generator is a TypeError.
  • History: generator-based coroutines (PEP 342 send, PEP 380 yield from, @asyncio.coroutine) led to async/await in PEP 492 (3.5); @asyncio.coroutine is gone in 3.11.
  • The bottom of every await chain is a yield to the event loop β€” "a coroutine is a generator with a different job and a stricter type".

Code / implementation expected: Optional β€” showing next() on a generator vs send(None) on a coroutine, or a toy event loop.

  • generators
  • coroutines

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA generator and a coroutine side by side
PythonCoroutines are driven by send(): a tiny event loop

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 130 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How does the asyncio event loop schedule coroutines?

Continue