🎓 A1Learner
🔍

Python Asyncio Basics

A coroutine is a function defined with async def. A coroutine can pause and let other work run.

Define a coroutine function

You add the word async before def.

async def greet():
    print("Hello")

Run a coroutine

asyncio.run() starts the event loop for you.

import asyncio

async def greet():
    print("Hello")

asyncio.run(greet())

Await a coroutine

await pauses this coroutine until the other one ends.

import asyncio

async def inner():
    return 42

async def main():
    value = await inner()
    print(value)

asyncio.run(main())

Pause with sleep(0)

Sleeping for zero seconds hands control back. No real time passes.

import asyncio

async def main():
    print("Start")
    await asyncio.sleep(0)
    print("After pause")

asyncio.run(main())

Example

import asyncio

async def greet(name):
    await asyncio.sleep(0)
    print(f"Hello, {name}")

async def main():
    await greet("Ana")
    await greet("Ben")

asyncio.run(main())

Key points

  • Coroutine: a function declared with async def.
  • Calling a coroutine function returns a coroutine object.
  • That object does no work until you await it.
  • Use await to run a coroutine and collect its result.
  • Use asyncio.run() to start one coroutine from normal code.
  • Event loop: the runner that runs coroutines and switches at await points.
  • Asyncio uses one thread that takes turns at await points.
  • A coroutine is not a thread.

In this example, greet() is a coroutine function. main() awaits greet("Ana") first. That call sleeps for zero seconds and then prints its line. Only then does main() await greet("Ben"). The awaits set the print order. asyncio.run(main()) starts the event loop and runs main().

Note

It switches only when it reaches await.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What happens when you call a function defined with async def?