Summary - Async basics
- Python course
- Advanced
- Lesson 30/83
- 5 min
Combine async/await and create_task to write a parallel downloader.
Summary - Async basics
This group covered async basics. async def declares a coroutine; await marks waiting points; asyncio.run runs from the top; asyncio.sleep waits without blocking; create_task creates a background Task.
The final task combines async def, await and asyncio.run: you'll call one coroutine from another with await.
Practice async def + await combined
Start with import asyncio. The function async def inner() returns 5. The function async def fetch() does return await inner() + 1. Add print(asyncio.run(fetch())).
Starter code
# import the asyncio module
# declare a coroutine named inner; return 5
# declare a coroutine named fetch; await inner, add 1 and return
# print fetch result via asyncio.runSample solution
import asyncio
async def inner():
return 5
async def fetch():
return await inner() + 1
print(asyncio.run(fetch()))Expected output
6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which function runs a coroutine from the top?
- asyncio.run Correct answer
- create_task
- asyncio.sleep
- time.sleep
Explanation: asyncio.run runs a coroutine from the top.
2 Summary: async/await
async def fetch():
____ inner()
async def fetch():
await inner()
Explanation: await inner() waits for another coroutine.
3 Match the group tools
| Term | Meaning |
|---|---|
async def |
Declares a coroutine |
await |
Waiting point |
asyncio.run |
Runs from the top |
create_task |
Background Task |