Coroutine

noun

say it: “KOH-roo-teen” /ˈkoʊruˌtin/

What calling an async def function gives you: a piece of work that can pause and resume, and that runs only when it's awaited or handed to asyncio.

What is a coroutine?

A coroutine is what you get by calling an async def function: a task that can pause and resume. It only runs when you await it or hand it to asyncio.

import asyncio

async def send_email(to):
    await asyncio.sleep(1)
    print(f"Sent to {to}")

task = send_email("ana@example.com")   # nothing runs yet
asyncio.run(task)                       # now it runs

In a sentence

  • “Calling fetch_rating() without await gave a coroutine, not a rating.”
  • “asyncio.gather ran three coroutines at once.”

Level: Freelancer · More Python terms at this level

Updated