Async
Async Await
An async def function returns a coroutine object when called. The function body has not produced its final result yet.
Source
import asyncio
async def fetch_title(slug):
await asyncio.sleep(0)
return slug.replace("-", " ").title()
coroutine = fetch_title("async-await")
print(coroutine.__class__.__name__)
coroutine.close()Output
coroutineUse await inside another coroutine to get the eventual result. asyncio.run() starts an event loop for the top-level coroutine.
Source
async def main():
title = await fetch_title("async-await")
print(title)
asyncio.run(main())Output
Async Awaitasyncio.gather() awaits several awaitables and returns their results in order. This is the shape used when independent I/O operations can progress together.
Source
async def main():
titles = await asyncio.gather(fetch_title("json"), fetch_title("datetime"))
print(titles)
asyncio.run(main())Output
['Json', 'Datetime']async with and async for are the asynchronous forms of context managers and iteration. A class implements __aenter__/__aexit__ to act as an async context manager; an async def function with yield becomes an async generator. The dedicated [async iteration and context](/iteration/async-iteration-and-context) page explains the protocols in depth.
Source
class Session:
async def __aenter__(self):
print("open")
return self
async def __aexit__(self, *_):
print("close")
return False
async def stream():
for slug in ["json", "datetime"]:
await asyncio.sleep(0)
yield slug
async def driver():
async with Session():
async for slug in stream():
print(slug)
asyncio.run(driver())Output
open
json
datetime
closeNotes
- Calling an async function creates a coroutine object.
awaityields control until an awaitable completes.- Workers request handlers are async, so this pattern appears around fetches and bindings.
- Prefer ordinary functions when there is no awaitable work to coordinate.
See also
- related: Async Iteration and Context
- prerequisite: Functions
- prerequisite: Context Managers
Run the complete example
Expected output
Async Await
['Json', 'Datetime']
open
json
datetime
close
Execution time appears here after you run the example.