Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen async and await Keywords | The Asyncio Foundation
Python Asyncio in Depth

async and await Keywords

Swipe um das Menü anzuzeigen

Two keywords power everything in asyncio: async and await. Understanding exactly what each one does – and when to use it – is the foundation for writing correct async code.

async def – Defining a Coroutine

Adding async before def turns a regular function into a coroutine function. Calling it does not execute the body – it returns a coroutine object that the event loop can schedule.

123456789101112131415
import asyncio import nest_asyncio nest_asyncio.apply() # Defining a coroutine function async def greet(name): print(f"Hello, {name}!") # Calling it returns a coroutine object, not the result result = greet("Alice") print(type(result)) # <class 'coroutine'> # Running the coroutine properly asyncio.run(greet("Alice"))

A coroutine only runs when it is either awaited or passed to asyncio.run().

await – Suspending Execution

await can only be used inside an async def function. It does two things:

  • Suspends the current coroutine until the awaited operation completes;
  • Hands control back to the event loop so other tasks can run.
123456789101112131415
import asyncio import httpx import nest_asyncio nest_asyncio.apply() # Fetching a post title using await async def fetch_post_title(post_id): url = f"https://jsonplaceholder.typicode.com/posts/{post_id}" async with httpx.AsyncClient() as client: response = await client.get(url) # Suspending here data = response.json() print(f"Post {post_id}: {data['title']}") asyncio.run(fetch_post_title(1))

The await client.get(url) line suspends fetch_post_title while the HTTP request is in flight. The event loop is free to run other coroutines during that time.

What You Can await

Not everything can be awaited. The await keyword only works with awaitables – objects that implement the __await__ method:

  • Coroutines (functions defined with async def);
  • asyncio.Task objects;
  • asyncio.Future objects;
  • Objects from libraries built for asyncio (like httpx, aiofiles).
123456789101112131415
import asyncio import nest_asyncio nest_asyncio.apply() # Awaiting another coroutine from within a coroutine async def fetch_data(): await asyncio.sleep(1) # Awaiting a built-in asyncio awaitable return "data ready" async def process(): result = await fetch_data() # Awaiting a coroutine print(result) asyncio.run(process())

Common Mistakes

1234567891011
import asyncio # Wrong: calling an async function without await async def main(): result = asyncio.sleep(1) # Returning a coroutine object – never runs print(result) # <coroutine object sleep at 0x...> # Correct: awaiting the coroutine async def main(): result = await asyncio.sleep(1) print("Done")

If you forget await, the coroutine object is created but never executed. Python will warn you with RuntimeWarning: coroutine was never awaited.

question mark

What does calling an async def function without await return?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 4

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 4
some-alt