Skip to content

Coroutines and await

async def creates a coroutine function

coroutine_def.py
import asyncio
 
 
async def say_hi():
    await asyncio.sleep(0.1)
    return "hi"
coroutine_def.py
import asyncio
 
 
async def say_hi():
    await asyncio.sleep(0.1)
    return "hi"

Calling vs awaiting

Calling a coroutine function returns a coroutine object.

calling_vs_awaiting.py
import asyncio
 
 
async def say_hi():
    await asyncio.sleep(0.1)
    return "hi"
 
 
async def main():
    c = say_hi()          # coroutine object (NOT executed yet)
    msg = await say_hi()  # executed
    print(type(c))
    print(msg)
 
 
asyncio.run(main())
calling_vs_awaiting.py
import asyncio
 
 
async def say_hi():
    await asyncio.sleep(0.1)
    return "hi"
 
 
async def main():
    c = say_hi()          # coroutine object (NOT executed yet)
    msg = await say_hi()  # executed
    print(type(c))
    print(msg)
 
 
asyncio.run(main())

await points

You can only use awaitawait inside an async defasync def function.

If you need to run async code from normal code, use:

  • asyncio.run(main())asyncio.run(main()) (most common)

Common mistake

This does nothing useful:

wrong.py
async def main():
    say_hi()  # forgot await
wrong.py
async def main():
    say_hi()  # forgot await

Because the coroutine is created but never awaited.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Your First Coroutine

Exercise 2 โ€“ await asyncio.sleep

Exercise 3 โ€“ Gather Two Coroutines

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did