Part 2 · Section 12

Generator Based Coroutines

So far generators have been a way to produce values lazily. But a generator is really a function that can pause and resume while keeping its local state, and that idea goes much further than iteration. If the caller can also hand data back in each time it resumes the generator, the generator becomes a coroutine: a routine that cooperates with others by voluntarily giving up control.

This is the machinery that Python’s async/await grew out of. Modern code writes native coroutines with async def, but the mechanics (suspension, resumption, sending values in, throwing exceptions in, delegating with yield from) are exactly what you’ll learn here, using plain generators you can poke at line by line.

In this section you’ll learn:

Lectures

  1. 01Coroutines✓
  2. 02Generator States✓
  3. 03Generator States✓
  4. 04Sending Data To Generators✓
  5. 05Closing Generators✓
  6. 06Sending Exceptions to Generators✓
  7. 07Using Decorators to Prime Coroutines✓
  8. 08Yield From - Two-Way Communications✓
  9. 09Yield From - Sending Data✓
  10. 10Yield From - Closing and Return✓
  11. 11Yield From - Throwing Exceptions✓
  12. 12Pipelines - Pulling Data✓
  13. 13Pipelines - Pushing Data✓
  14. 14Pipelines - Broadcasting✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →