What is async await in Python: Simple Explanation and Example
async and await in Python are keywords used to write asynchronous code that can pause and resume tasks without blocking the whole program. They help run multiple operations at the same time, making programs faster and more efficient when waiting for things like files or network data.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of just standing there doing nothing, you start chopping vegetables. This is similar to how async and await work in Python. When a task needs to wait (like waiting for water to boil or data to load), the program can pause that task and do other things instead of waiting idly.
In Python, marking a function with async means it can pause its work at certain points using await. When the program hits await, it pauses that function and lets other tasks run. Once the awaited task finishes, the function resumes. This way, Python can handle many tasks efficiently without waiting for each one to finish before starting the next.
Example
This example shows a simple asynchronous function that waits for a short time before printing a message. It runs two tasks at the same time without waiting for one to finish before starting the other.
import asyncio async def say_after(delay, message): await asyncio.sleep(delay) print(message) async def main(): task1 = asyncio.create_task(say_after(1, 'Hello')) task2 = asyncio.create_task(say_after(2, 'World')) print('Started tasks') await task1 await task2 print('Finished tasks') asyncio.run(main())
When to Use
Use async and await when your program needs to do many things that involve waiting, like downloading files, reading databases, or handling many users at once. Instead of waiting for each task to finish, asynchronous code lets your program keep working on other tasks.
This is very useful in web servers, chat applications, or any program that handles many input/output operations without blocking the whole program.
Key Points
- async marks a function as asynchronous, allowing it to pause.
- await pauses the function until the awaited task finishes.
- Asynchronous code improves efficiency by running multiple tasks concurrently.
- It is best for I/O-bound tasks like network calls or file operations.