Concept Explanation
Imagine you are a chef in a restaurant.
- Synchronous (Normal) Python: You start cooking a steak. You stand in front of the stove and wait 10 minutes for it to finish, doing absolutely nothing else. Only once the steak is plated can you start boiling water for pasta.
- Asynchronous (AsyncIO) Python: You start the steak. Instead of waiting, you set a timer and immediately start boiling the water. When the water boils or the steak is done, you "switch back" to handle it. You are one person, but you are handling many tasks at once by not waiting for "slow" things to finish.
AsyncIO is the library that lets Python perform this "multi-tasking" behavior. It is especially useful for tasks that involve Waiting, like waiting for a website to respond, waiting for a file to download, or waiting for a database to return data.
Syntax or Core Structure
Coroutines: The Building Blocks
You define an asynchronous function using the async def keyword. This function is called a "Coroutine." To run a coroutine, you must await it.
import asyncio
async def say_hello():
print("Hello...")
await asyncio.sleep(1) # Pause here while the "timer" runs
print("...World!")
# You can't just call it like say_hello(). You must use:
asyncio.run(say_hello())
The await keyword
The await keyword can only be used inside an async def function. It tells Python: "This task is going to take a while (like a network request). Feel free to go do other tasks while I wait for this one to finish."
Code Example #1 (Basic)
Defining and running a simple asynchronous routine.
import asyncio
async def brew_coffee():
print("☕ Starting coffee...")
await asyncio.sleep(2) # Simulates a slow process
print("☕ Coffee is ready!")
async def toast_bread():
print("🍞 Starting toast...")
await asyncio.sleep(1)
print("🍞 Toast is ready!")
async def main():
# Still running one after another here
await brew_coffee()
await toast_bread()
asyncio.run(main())
Code Example #2 (Intermediate)
Using asyncio.create_task() to start tasks simultaneously.
import asyncio
import time
async def fetch_data(id, delay):
print(f"Fetching data {id}...")
await asyncio.sleep(delay)
return f"Data {id} received"
async def main():
start = time.perf_counter()
# Start both tasks at the same time
task1 = asyncio.create_task(fetch_data(1, 3))
task2 = asyncio.create_task(fetch_data(2, 2))
# Now wait for them to finish
result1 = await task1
result2 = await task2
end = time.perf_counter()
print(f"Total time: {end - start:.2f} seconds") # Should be ~3s, not 5s!
asyncio.run(main())
Real World Example
Batch Web Scraper: Imagine you need to check the status of 100 websites. If you do it one-by-one, it might take minutes. If you do it asynchronously, it might take seconds.
import asyncio
async def check_site(site_name):
print(f"Checking {site_name}...")
# In a real app, you'd use 'aiohttp' here
await asyncio.sleep(1)
print(f"Finished {site_name}")
async def main():
sites = ["Google", "Facebook", "Twitter", "GitHub", "StackOverflow"]
# Create a list of tasks
tasks = [asyncio.create_task(check_site(s)) for s in sites]
# Run all tasks and wait for them to finish
for t in tasks:
await t
asyncio.run(main())
Common Mistakes
- Forgetting
await: If you callsay_hello()withoutawait, the function will return a "Coroutine Object" but won't actually execute the code inside. - Using
time.sleep(): Never usetime.sleep()in an async function! It blocks the entire program, including every other task. Always useawait asyncio.sleep(). - Calling
asyncio.run()multiple times: You should usually only callasyncio.run()once at the very top level of your program.
Best Practices
- Async all the way down: Once you start using async, try to use async-compatible libraries (like
aiohttpinstead ofrequests) for all your I/O tasks. - Use Tasks for Concurrency: Simply calling
await func()one after another is still slow. Useasyncio.gather()orcreate_task()to run things at the same time. - Handle Exceptions: Wrap your awaits in try-except blocks, as network tasks often fail.
Practice Exercises
- The Countdown: Create an async function
countdown(n)that prints numbers fromndown to 1, waiting 1 second between each. - Double Runner: Create two different coroutines and use
create_taskto run them simultaneously. Verify that they finish in the time of the longest task, not the sum of both. - The Traffic Light: Simulate a traffic light (Green for 5s, Yellow for 2s, Red for 5s) using async and await in a loop.