Async

Async Await

async def creates coroutines, and await pauses until awaitable work completes.

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

coroutine
LOOPCOROawaitresume
On await, the coroutine yields to the loop; the loop runs other work and resumes when the awaitable is ready.

Use 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 Await

asyncio.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
close

Notes

See also

Run the complete example

Example code

Expected output

Async Await
['Json', 'Datetime']
open
json
datetime
close

Execution time appears here after you run the example.