async and await Keywords
Sveip for å vise menyen
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.
123456789101112131415import 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.
123456789101112131415import 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.Taskobjects;asyncio.Futureobjects;- Objects from libraries built for asyncio (like
httpx,aiofiles).
123456789101112131415import 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
1234567891011import 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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår