async def
- Python course
- Advanced
- Lesson 27/83
- 5 min
Learn to define coroutines with async def.
async def
async def declares a coroutine function. It takes parameters and returns a value like a normal def; but calling it returns a coroutine instead of a result.
async def add(a, b):
return a + bInside, you can await other coroutines with await; that is what sets it apart from a normal function. await is not required; the coroutine can be defined without it.
In async def functions, the return value goes to the awaiter; without a return, None comes back.
Coroutine and return
Inside an async def, writing return value sends that value to the awaiter. Example: async def fetch(): ...; return data. The caller does data = await fetch().
A coroutine can have a single return; multiple returns can be used for branching but only the first reached runs.
Without a return value, None comes back; just like in normal functions.
Practice Write async def add
The function async def add(a, b) does return a + b. Start with import asyncio. Add print(asyncio.run(add(3, 4))).
Starter code
# import the asyncio module
# declare a coroutine named add; return the sum of two params
# print the result of add(3, 4) via asyncio.runSample solution
import asyncio
async def add(a, b):
return a + b
print(asyncio.run(add(3, 4)))Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the async def parts
| Term | Meaning |
|---|---|
async |
Marker keyword |
def |
Function declaration |
return |
Returns a value |
await |
Can wait |
2 What happens if there is no return inside async def?
- It raises an error
- None is returned Correct answer
- An empty coroutine is returned
- True is returned
Explanation: Without return in async def, None comes back; like a normal function.
3 async def return
async def add(a, b):
____ a + b
async def add(a, b):
return a + b
Explanation: return sends the value to the awaiter.