Kritim Yantra
Apr 17, 2025
If you’ve ever worked with async functions in Python, you’ve likely encountered asyncio
. This powerful module allows Python programs to perform multiple operations concurrently, making it ideal for I/O-bound tasks like web scraping, API calls, and handling thousands of socket connections.
In this blog, we’ll explore:
asyncio
isasyncio
?asyncio
is Python’s built-in library that provides a framework for writing asynchronous programs using:
It enables single-threaded concurrency using cooperative multitasking — meaning, instead of multiple threads, tasks voluntarily pause and give others a chance to run.
Concept | Description |
---|---|
Event Loop | Manages and schedules asynchronous tasks |
Coroutine | A special function declared with async def , that can be paused with await |
Task | A wrapper that schedules a coroutine to run |
Future | A low-level placeholder for a result that hasn’t been computed yet |
The event loop is the beating heart of asyncio. It controls the execution of coroutines.
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(main()) # Starts the event loop
Without the event loop, await
would never resume!
import asyncio
async def say_hello():
print("Hi!")
await asyncio.sleep(1)
print("Bye!")
asyncio.run(say_hello())
import asyncio
async def task(name):
print(f"{name} started")
await asyncio.sleep(2)
print(f"{name} finished")
async def main():
await asyncio.gather(
task("Task 1"),
task("Task 2"),
task("Task 3")
)
asyncio.run(main())
All three tasks start together and finish almost simultaneously!
create_task()
Sometimes, you want to start a coroutine without waiting for it immediately.
async def delayed_message(msg, delay):
await asyncio.sleep(delay)
print(msg)
async def main():
task = asyncio.create_task(delayed_message("Hello after 3s", 3))
print("Doing other stuff...")
await task
asyncio.run(main())
Mistake | Fix |
---|---|
Forgetting to await |
Always use await with coroutines |
Using time.sleep() |
Use await asyncio.sleep() instead |
Blocking the event loop | Avoid long CPU tasks inside async code |
Calling asyncio.run() inside a running loop |
Don’t nest asyncio.run() (e.g., in Jupyter) |
Using aiohttp
with asyncio
:
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
print(f"Fetched {url} with status {response.status}")
async def main():
urls = ['https://example.com', 'https://python.org', 'https://github.com']
tasks = [fetch(url) for url in urls]
await asyncio.gather(*tasks)
asyncio.run(main())
All requests are made concurrently, which is much faster than sync methods.
✅ Use asyncio.run()
as your entry point
✅ Use asyncio.gather()
for concurrent execution
✅ Avoid blocking functions like time.sleep()
or requests.get()
✅ Break large I/O-bound tasks into small coroutines
✅ Choose async libraries like aiohttp
, aiosqlite
, etc.
Feature | Description |
---|---|
asyncio.run() | Starts the event loop |
async def | Defines a coroutine |
await | Pauses and resumes coroutine |
gather() | Runs multiple coroutines concurrently |
create_task() | Starts a coroutine in the background |
Now that you know asyncio
, you’re ready to build high-performance applications:
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google