Asynchronous Programming in Python
Asynchronous programming allows you to write code that performs tasks concurrently, improving efficiency, especially in I/O-bound applications. Python provides powerful tools like async, await, and the asyncio module to help you write non-blocking code.
What You'll Learn
You will learn how to use async and await in Python to make your programs do many things at once. Instead of waiting for one task to finish, your program can start another task and come back later—making it faster and more efficient.
Basic Structure of Async in Python
Asynchronous programming lets Python do other things while waiting — for example, waiting for a web page to load or a file to save. Instead of stopping everything, Python can keep going and come back to finish the waiting task later.
To write asynchronous code, Python uses special keywords: async and await.
async and await keywords enable asynchronous function definitions and coroutine management. They're crucial for writing non-blocking code, particularly in I/O operations such as API calls or file handling.
- async def: Declares a coroutine function.
- await: Pauses execution until the awaited coroutine completes.
Here’s the basic structure:
import asyncio
# Step 1: Create an async function
async def greet():
print("Hello...")
await asyncio.sleep(2) # Step 2: Wait without blocking
print("...World!")
# Step 3: Run the async function
asyncio.run(greet())
import asyncio
# Step 1: Create an async function
async def greet():
print("Hello...")
await asyncio.sleep(2) # Step 2: Wait without blocking
print("...World!")
# Step 3: Run the async function
asyncio.run(greet())
What's happening here:
- import asyncio: This brings in Python’s built-in asyncio module, which helps you write and run asynchronous code.
- async def: This tells Python you're writing an asynchronous function.
- await: This tells Python to pause here and do something else while it waits.
- asyncio.sleep(2): This just makes Python wait 2 seconds (like a timer).
- asyncio.run(): This starts running your async code.
Output:
Hello...
...World!
Hello...
...World!
So instead of stopping everything to wait, Python can take a quick break, then come back and finish the job. This is super helpful for apps that download files, load websites, or talk to databases!
What Is an Event Loop?
When you use async in Python, there’s something working behind the scenes that keeps everything running smoothly — it’s called the event loop.
Think of the event loop as a manager that keeps track of all the tasks that are “waiting” and decides when to run them. It checks when each task is ready and moves on to the next one without blocking the whole program.
Python uses the asyncio module to handle the event loop for you. You don’t usually have to control it directly, but it helps to understand what’s happening.
Example: Manually Using the Event Loop
In some advanced cases, you might use the event loop manually, like this:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
# Create an event loop manually
loop = asyncio.get_event_loop()
loop.run_until_complete(say_hello())
loop.close()
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
# Create an event loop manually
loop = asyncio.get_event_loop()
loop.run_until_complete(say_hello())
loop.close()
How It Works
- The event loop starts and waits for tasks to run.
- When you await something (like a sleep or web request), it lets other tasks run.
- Once the waiting is done, the loop comes back and finishes that task.
- This helps your program stay responsive and efficient — especially for things like web servers or file operations.
Output:
Hello
World
Hello
World
In most modern Python code, you’ll use asyncio.run() instead, which handles the loop for you:
asyncio.run(say_hello())
asyncio.run(say_hello())
The event loop is what makes async code work — it helps Python switch between tasks quickly without waiting around!
Example 1: Running Two Tasks at the Same Time
Let's say we have two functions — one that waits for 2 seconds, and another that waits for 1 second. Normally, they would run one after the other and take 3 seconds total. But with async, they can run at the same time!
import asyncio
async def task_one():
print("Task 1 started")
await asyncio.sleep(2)
print("Task 1 done")
async def task_two():
print("Task 2 started")
await asyncio.sleep(1)
print("Task 2 done")
async def main():
await asyncio.gather(task_one(), task_two())
asyncio.run(main())
import asyncio
async def task_one():
print("Task 1 started")
await asyncio.sleep(2)
print("Task 1 done")
async def task_two():
print("Task 2 started")
await asyncio.sleep(1)
print("Task 2 done")
async def main():
await asyncio.gather(task_one(), task_two())
asyncio.run(main())
🔍 How It Works
- task_one() and task_two() are both async functions that pause using await asyncio.sleep().
- asyncio.gather() starts both tasks at the same time.
- The event loop runs task_one, then switches to task_two while waiting for the 2-second pause.
- Since task_two only takes 1 second, it finishes first — even though it started at the same time as task_one.
- This way, the total time is just 2 seconds (the longest task), not 3.
Output
Task 1 started
Task 2 started
Task 2 done
Task 1 done
Task 1 started
Task 2 started
Task 2 done
Task 1 done
🚀 This is the power of async: your program doesn’t have to wait for one thing to finish before starting another!
💡 Even though Task 1 takes longer, both tasks start at the same time. Python uses await and the event loop to keep things moving — no time wasted!
Frequently Asked Questions
What is async and await in Python?
What is async and await in Python?
async and await are keywords used to write asynchronous code that lets your program run tasks at the same time without waiting for each to finish.
When should I use asynchronous programming?
When should I use asynchronous programming?
It’s best for operations that take time, like network requests or reading files, so your program doesn’t freeze while waiting.
How is async different from threading?
How is async different from threading?
Async uses an event loop to switch between tasks efficiently, while threading runs multiple threads at once. Async is usually better for tasks waiting on external resources.
Do I need special libraries for async/await?
Do I need special libraries for async/await?
Python has a built-in library called asyncio that helps you write async code, but some other libraries also support it.
Can async functions call regular functions?
Can async functions call regular functions?
Yes, async functions can call normal synchronous functions, but synchronous code cannot wait for async functions to finish.
What's Next?
Now that you know the basics of asynchronous programming, the next step is learning how to run multiple tasks at the same time. You’ll see how Python can start several tasks together and handle them efficiently using asyncio.