APIs and Async · Async Python · lesson 6 of 12
async and await
about 16 minutes · free · runs in your browser
Waiting without blocking
Most of the time an HTTP client is not computing anything — it is waiting. asyncio
lets one thread hold many such waits at once.
import asyncio
async def greet(name):
await asyncio.sleep(0.1) # a stand-in for waiting on a network
return "Hello, " + name
asyncio.run(greet("Ada")) # 'Hello, Ada'
Three rules:
async defmakes a coroutine function. Calling it does not run it — it returns a coroutine object.awaitruns a coroutine and waits for its result. It is only legal insideasync def.- Something has to start the whole thing.
asyncio.run(main())is that something.
The most common beginner bug is forgetting await, which leaves you holding a
coroutine object instead of a value — and Python warns "coroutine was never awaited".
Your turn: write an async double(n) that waits briefly and returns n * 2, and
an async main() that awaits it for 5 and returns the result. Call it with
asyncio.run.
You start from this, and edit it in the browser:
import asyncio
async def double(n):
pass
async def main():
pass
result = None