Kritim Yantra
Apr 17, 2025
In the world of modern software development, speed and efficiency matter more than ever. Python's async
functions help us build non-blocking, high-performance applications — especially useful when dealing with I/O operations, like APIs, databases, or file systems.
In this blog post, we'll break down:
async
/await
)An async function is a special type of function that can perform non-blocking operations. It uses async def
instead of regular def
and is used with await
to pause and resume tasks.
async def greet(name):
print(f"Hello, {name}")
Calling this function won’t execute it like a normal function. It returns a coroutine that must be awaited or run using an event loop.
Async functions shine when you want to:
Example:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(2)
print("World")
asyncio.run(say_hello())
Here, the program doesn’t freeze during sleep
. Instead, it “awaits” asynchronously.
Term | Description |
---|---|
async def |
Defines an asynchronous function |
await |
Waits for an async operation to complete |
coroutine |
A special object returned by an async function |
asyncio |
Python’s built-in async library for managing event loops and tasks |
Let’s compare a simple web request using both approaches.
import time
def fetch_data():
time.sleep(2)
return "Data"
print(fetch_data()) # Blocks for 2 seconds
import asyncio
async def fetch_data():
await asyncio.sleep(2)
return "Data"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main()) # Runs without freezing the program
Async version lets other tasks run during the sleep
.
import asyncio
async def download(file):
print(f"Downloading {file}...")
await asyncio.sleep(2)
print(f"{file} downloaded!")
async def main():
await asyncio.gather(
download("file1.txt"),
download("file2.txt"),
download("file3.txt")
)
asyncio.run(main())
All 3 downloads happen concurrently, not one by one. Huge performance boost!
Calling async functions like normal ones:
result = fetch_data() # ❌ Wrong, returns coroutine
✅ Correct:
result = await fetch_data()
Mixing sync I/O in async code:
# Avoid time.sleep()
await asyncio.sleep() instead
Not using asyncio.run()
in main thread
Use async when your code:
Avoid async if:
aiohttp
– Async HTTP requestsaiomysql
, asyncpg
– Async database clientsFastAPI
, Sanic
– Async web frameworksQuart
– Async Flask alternativeasync def
and await
properlyasyncio.run()
and asyncio.gather()
Async functions in Python open the doors to building scalable, responsive, and high-performance applications — from APIs to bots and beyond.
Mastering async
and await
will make you a more modern and efficient Python developer, especially in the age of real-time apps and APIs.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google