CodeBlanks Logo Icon CodeBlanks

async/await

Learn the async and await keywords.

async/await

async/await is syntax that makes concurrent code readable. You define a function with async def; inside, you wait for another concurrent operation with await.

async def greet(name):
    return "Hello, " + name

Calling an async def function does not run it immediately; it returns a coroutine object. Running it needs an event loop, which we'll cover in the next lesson.

You mark waiting points with await; while waiting, the event loop can run other work.

Waiting with await

You wait for a coroutine or awaiting operation with await. It tells the event loop "I can wait here, do other work".

await is valid only inside async def; using it outside raises an error. The expression next to await must be an awaitable: a coroutine, task or future.

async def fetch():
    await asyncio.sleep(1)
    return "ok"

Here await lets the event loop run other work while asyncio.sleep is pending.

Practice Write greet with async def

The function async def greet(name) returns "Hello, " + name. Then call print(asyncio.run(greet("Ayşe"))). Start with import asyncio.

Starter code

main.py
# import the asyncio module
# declare a coroutine named greet; return a greeting string with the name
# print the result of greet("Ayşe") via asyncio.run

Sample solution

main.py
import asyncio

async def greet(name):
    return "Hello, " + name

print(asyncio.run(greet("Ayşe")))

Expected output

Hello, Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an async def function return when called directly?

  • It raises an error
  • The function result
  • None
  • A coroutine object Correct answer

Explanation: Calling async def does not run it; it returns a coroutine object.

2 Complete async def

Question
____ def greet(name):
    return "Merhaba, " + name
Answer
async def greet(name):
    return "Merhaba, " + name

Explanation: async def declares a coroutine function.

3 Match the async/await concepts

Term Meaning
async def Coroutine definition
await Waiting point
coroutine Runnable object
event loop Running mechanism

All lessons in Advanced