Mastering Python Asyncio: Non-Blocking, Fast Code
Asyncio is Python’s toolkit for asynchronous programming. With async
and await
, you can run tasks in parallel without threads—perfect for APIs, scraping, and networking apps.
🆚 Synchronous vs Asynchronous
# Synchronous version
import time
def fetch_data():
time.sleep(2)
return "Data received"
print(fetch_data())
# Asynchronous version
import asyncio
async def fetch_data():
await asyncio.sleep(2)
return "Data received"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Note: await
pauses without blocking, letting the CPU run other tasks!
⚙️ The Event Loop
Asyncio uses an event loop to schedule and resume tasks. Think of it as a task manager that lets functions pause and resume without losing context.
🔄 Running Multiple Tasks
import asyncio
async def say_hello():
await asyncio.sleep(1)
print("Hello")
async def say_world():
await asyncio.sleep(1)
print("World")
async def main():
task1 = asyncio.create_task(say_hello())
task2 = asyncio.create_task(say_world())
await task1
await task2
asyncio.run(main())
✅ Output: Both tasks finish in 1 second instead of 2!
🌍 Real-Life Example: Fetch Multiple URLs
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://httpbin.org/get",
"https://api.github.com",
"https://example.com"
]
tasks = [fetch(url) for url in urls]
results = await asyncio.gather(*tasks)
for r in results:
print(r[:100]) # Print preview
asyncio.run(main())
⚡ This is faster than using
requests
in a loop—everything runs concurrently!
🚫 Common Mistakes
- ❌ Forgetting
await
— nothing will run! - ❌ Using
time.sleep()
inside async functions. Useasyncio.sleep()
instead. - ❌ Nesting
asyncio.run()
inside Jupyter or another event loop.
📌 When Should You Use Asyncio?
- Multiple I/O-bound tasks (API calls, file access, DB queries)
- Thousands of concurrent tasks
- Building fast bots, web scrapers, or microservices
🧠 Summary
async
defines a coroutine.await
pauses and resumes the function.asyncio.run()
launches the event loop.asyncio.gather()
runs multiple coroutines concurrently.
📚 Learn More
Follow DarchumsTech for more advanced Python tutorials weekly!
Comments
Post a Comment