How to Use await in Python: Simple Async Await Guide
In Python, use
await inside an async function to pause execution until an asynchronous operation completes. This lets your program handle other tasks while waiting, improving efficiency.Syntax
The await keyword is used inside an async function to pause its execution until the awaited asynchronous operation finishes. The basic syntax is:
async def: declares an asynchronous function.await: pauses the function until the awaited coroutine or async task completes.
python
async def my_function(): result = await some_async_operation() return result
Example
This example shows how to use await to pause an async function while waiting for a simulated delay, then print the result.
python
import asyncio async def say_hello(): print('Waiting...') await asyncio.sleep(2) # Pause here for 2 seconds print('Hello after 2 seconds!') asyncio.run(say_hello())
Output
Waiting...
Hello after 2 seconds!
Common Pitfalls
Common mistakes when using await include:
- Using
awaitoutside anasyncfunction causes a syntax error. - Not running the async function properly with
asyncio.run()or an event loop. - Forgetting that
awaitonly works with awaitable objects like coroutines or tasks.
python
import asyncio # Wrong: await outside async function # await asyncio.sleep(1) # SyntaxError # Right way: async def correct(): await asyncio.sleep(1) asyncio.run(correct())
Quick Reference
Remember these tips when using await in Python:
- Only use
awaitinsideasync deffunctions. - Use
asyncio.run()to start your async functions from regular code. awaitpauses the function but does not block the whole program.
Key Takeaways
Use
await only inside async functions to pause until async tasks finish.Start async functions with
asyncio.run() to run them properly.await improves efficiency by letting other tasks run while waiting.You cannot use
await in regular (non-async) functions.Only await awaitable objects like coroutines or tasks.