Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 40 ยท Getting Started

Your First Coroutine: async def and await

Write your first Python coroutine with async def, call it correctly, use await to pause and resume, and avoid the classic mistake of forgetting await.

A coroutine is a function that can pause in the middle and continue later. You create one by writing async def instead of def. Inside it you may use the keyword await to say "pause here until this other thing is ready". While it is paused, the event loop is free to run other coroutines.

This lesson covers the two keywords, what calling a coroutine function really does, and the most common beginner mistake. After it you will be able to read almost any asyncio program.

async def creates a coroutine function

Compare a normal function with a coroutine function:

Python A normal function and a coroutine function

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.

Calling greet_sync("Ada") runs the body and returns the greeting. Calling greet_async("Ada") does not run the body at all. It returns a coroutine object: a paused job waiting to be started. Nothing happens until something drives it, either await or the event loop.

await runs a coroutine and waits for its result

Inside another coroutine, await starts a coroutine, pauses the caller until it finishes, and gives you its return value:

Python Awaiting a coroutine

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.

Read it top to bottom as if it were ordinary code, because that is the point of async/await: sequential-looking code that does not block. Notice that these two awaits run one after the other. Awaiting a coroutine directly does not make things concurrent. To overlap them you need tasks or gather, covered in Tasks and Gathering.

The rules to remember:

  1. await can only be used inside an async def function (or at the top level of an async-aware environment such as this site's runner).
  2. You can only await an awaitable: a coroutine object, a Task or a Future (more on those).
  3. An async def function with no await inside is legal, but it never pauses, so it gives no concurrency.

Running a coroutine from normal code

A normal def function or a plain script cannot use await. The bridge is asyncio.run(): it creates an event loop, runs one coroutine to completion, and closes the loop.

Python
import asyncio


async def main():
    print("inside the loop")
    return 42


answer = asyncio.run(main())   # call it once, at the entry point
print(answer)

Use exactly one asyncio.run() per program, at the very bottom. Everything else inside should simply await. The next lesson explains entry points in depth.

The classic mistake: forgetting await

Because calling a coroutine function only creates a coroutine object, forgetting await is a silent bug. The call "works" but its body never runs:

Python Forgetting await

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.

Only saving second is printed. Python also emits a RuntimeWarning: coroutine 'save' was never awaited when the unused coroutine object is garbage collected (you will see it in the output). That warning is your clue. Whenever you see it, look for a missing await.

Type checkers and linters such as mypy, pyright and Ruff flag unawaited coroutines before you ever run the code. Turn that check on.

await pauses only the current coroutine

When a coroutine reaches await asyncio.sleep(1), it is suspended and control goes back to the event loop. The loop can now run anything else that is ready. One second later the loop resumes the sleeper exactly where it stopped, with all its local variables intact. That is why coroutines are cheap: a paused coroutine is just a small object holding its position and variables, not an operating system thread.

sequenceDiagram
    participant Loop as Event loop
    participant A as Coroutine A
    Loop->>A: start
    A->>Loop: await sleep(1) (pause)
    Note over Loop: runs other work
    Loop->>A: timer done, resume
    A->>Loop: return result

A coroutine hands control to the loop at an await, and the loop hands it back when the wait is over.

Return values and exceptions work normally

A coroutine returns values with return, and an exception raised inside it surfaces at the await that was waiting for it. You can catch it with an ordinary try/except:

Python Errors travel through await

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.

No special error handling is needed for async code. Exceptions, try/finally, return and loops behave exactly as in synchronous Python.

async def with decorators, methods and lambdas

async def works on methods too, and you await the method call the same way. There is no async lambda; use a nested async def instead. A method that is async can be a @staticmethod or @classmethod, and special methods such as __aenter__ are asynchronous variants you will meet in async context managers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does calling an async def function, without await, return?

    The body does not run on the call. You get a coroutine object that something must await or schedule.
  2. 2. Where can the await keyword be used in a normal Python script?

    await is only legal inside a coroutine function (or an async-aware top level such as a notebook or this site's runner).
  3. 3. You write save('first') inside an async function and forget await. What happens?

    Only a coroutine object is created. The warning appears when it is discarded without being awaited.
  4. 4. Two awaits in a row, such as await a() then await b(), run how?

    Awaiting directly waits for each to finish. Concurrency needs tasks or gather.

Summary

  • async def defines a coroutine function; calling it returns a coroutine object without running anything.
  • await runs an awaitable, pauses the caller, and produces the result (or raises its exception).
  • Use one asyncio.run(main()) at the entry point.
  • Forgetting await is the most common mistake; look for the "never awaited" warning.
  • Plain await is sequential; concurrency comes from tasks.

Next: asyncio.run and entry points