Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 40 ยท Event Loop and Coroutines

Coroutines, Awaitables and __await__

Learn what makes an object awaitable in Python: coroutine objects, tasks, futures and custom __await__ classes, plus coroutine states and common mistakes.

You can only put await in front of an awaitable. Python has exactly three kinds: coroutine objects, Tasks and Futures. Knowing which is which explains many error messages, and it lets you write your own awaitable classes when a library demands one.

Kind 1: coroutine objects

Calling an async def function returns a coroutine object. It is awaitable, but it only starts running when something awaits it or schedules it. Coroutine objects are single-use: once finished, you cannot await them again.

Python A coroutine object is single use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Awaiting a finished coroutine raises RuntimeError: cannot reuse already awaited coroutine. If you need to run the same logic twice, call the function again to get a fresh coroutine object.

Kind 2: Tasks

A Task wraps a coroutine and schedules it on the loop to run in the background. asyncio.create_task(coro) returns it immediately. A Task can be awaited any number of times; each await simply gives the same result. Creating tasks covers them in depth.

Kind 3: Futures

A Future is an empty box for a result that will arrive later. Someone calls set_result() (or set_exception()), and everyone awaiting the future wakes up. Futures are the low-level building block under tasks, locks, queues and network code. See Futures and callbacks.

flowchart TD
    A["Awaitable"] --> C["Coroutine object<br/>from async def"]
    A --> F["Future<br/>result arrives later"]
    F --> T["Task<br/>a Future that runs a coroutine"]

A Task is a Future subclass: the future's "result" is whatever the wrapped coroutine returns.

You can ask Python what something is with these helpers:

Python Which objects are awaitable?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

inspect.isawaitable is the general test. inspect.iscoroutinefunction tells you whether a function was declared with async def, which is how libraries decide whether to call or await something.

Coroutine states

Every coroutine object is in one of four states, which you can inspect with inspect.getcoroutinestate: CORO_CREATED (not started), CORO_RUNNING, CORO_SUSPENDED (paused at an await) and CORO_CLOSED (finished or failed). The next example drives a coroutine by hand with send, which is what the event loop does behind the scenes:

Python Driving a coroutine by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You never do this in real programs. It simply shows that a coroutine is a resumable function: send(None) runs it to the next pause, and when it finishes, the return value comes back inside a StopIteration. The event loop is a very fast scheduler that calls send on many coroutines in turn.

Writing your own awaitable with __await__

Any class that defines __await__ (returning an iterator) is awaitable. The usual trick is to delegate to a future or to asyncio.sleep:

Python A custom awaitable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Custom awaitables are rare in application code. Most of the time you wrap behavior in a normal async def function instead, because it is simpler and gets better tracebacks.

Never-awaited coroutines and ensure_future

Creating a coroutine and dropping it triggers RuntimeWarning: coroutine ... was never awaited. Three correct ways to use a coroutine object are: await it, wrap it in asyncio.create_task, or pass it to asyncio.run or asyncio.gather. Older code uses asyncio.ensure_future, which turns any awaitable into a Future or Task. Prefer create_task for coroutines in new code.

Common mistakes

  • Awaiting the function instead of its result: await job (no parentheses) raises TypeError: object function can't be used in 'await' expression.
  • Awaiting a non-awaitable: await 5 is a TypeError too. Only awaitables work.
  • Using await in a normal def: this is a SyntaxError. Make the function async def.
  • Awaiting a blocking function such as await time.sleep(1): time.sleep returns None, so you get TypeError, and even without the await it would block the loop. Use asyncio.sleep.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is NOT awaitable?

    Awaitables are coroutine objects, Tasks, Futures and objects with await. An int has none.
  2. 2. What happens if you await the same coroutine object twice?

    Coroutine objects are single use. Call the function again for a new one.
  3. 3. How is a Task related to a Future?

    Task subclasses Future. Its result is the wrapped coroutine's return value.
  4. 4. What does await job (without parentheses) raise?

    You must call job() to get a coroutine object, which is awaitable.

Summary

  • Awaitables are coroutine objects, Tasks, Futures and any class with __await__.
  • A coroutine object is a resumable function and can be awaited only once; a Task or Future can be awaited many times.
  • Task is a Future subclass; futures are the primitive that wakes waiting coroutines.
  • Always await, schedule or pass coroutine objects to run or gather; never drop them.

Next: Futures and callbacks