Python basic to advance
43 subscribers
131 photos
98 links
Learn Python daily with bite-sized lessons, code examples, output previews, and fun quizzes. Perfect for beginners and enthusiasts!
Download Telegram
Day 27: Introduction to Flask/Django \- Code & Output
🚀 **Day 28: Diving into Asynchronous Programming with `asyncio`!** 🚀

Hello Python learners! 👋 Today, we're tackling one of Python's most powerful features for building high-performance, non-blocking applications: **Asynchronous Programming** using the `asyncio` library.

Asynchronous programming allows your program to perform multiple I/O-bound operations (like network requests, file operations, or waiting for external resources) concurrently without using multiple threads. This means your program can do other work while waiting for something to complete, making it much more efficient! Think faster web servers and more responsive applications. ⏱️🧠

Let's see a basic example of how `asyncio` works!

```python
import asyncio
import time

async def fetch_data(task_id, delay):
"""Simulates an I/O-bound operation."""
print(f"[{time.strftime('%H:%M:%S')}] Task {task_id}: Starting fetch (will take {delay}s)...")
await asyncio.sleep(delay) # Non-blocking wait
print(f"[{time.strftime('%H:%M:%S')}] Task {task_id}: Data fetched!")
return f"Data for task {task_id}"

async def main():
start_time = time.time()
print("Main: Kicking off multiple data fetches concurrently!")

# Run multiple coroutines concurrently
results = await asyncio.gather(
fetch_data("A", 3), # Task A takes 3 seconds
fetch_data("B", 1), # Task B takes 1 second
fetch_data("C", 2) # Task C takes 2 seconds
)

end_time = time.time()
print("nMain: All tasks completed!")
print(f"Main: Total execution time: {end_time - start_time:.2f} seconds.")
print("Main: Results received:", results)

if __name__ == "__main__":
asyncio.run(main())
```

**Output example:**
```
Main: Kicking off multiple data fetches concurrently!
[HH:MM:SS] Task A: Starting fetch (will take 3s)...
[HH:MM:SS] Task B: Starting fetch (will take 1s)...
[HH:MM:SS] Task C: Starting fetch (will take 2s)...
[HH:MM:SS] Task B: Data fetched!
[HH:MM:SS] Task C: Data fetched!
[HH:MM:SS] Task A: Data fetched!

Main: All tasks completed!
Main: Total execution time: 3.00 seconds.
Main: Results received: ['Data for task A', 'Data for task B', 'Data for task C']
```
*(Note: HH:MM:SS will be your actual current time.)*

See how all tasks started almost simultaneously, and the total execution time was determined by the *longest* task (3 seconds), not the sum of all tasks (3+1+2=6 seconds)? That's the power of `asyncio`! ✨

**Small Challenge:**
Modify the `main` function to add a fourth task, `fetch_data("D", 0.5)`. Observe how the total execution time remains the same (3.00s) because it's still less than the longest running task ("A"). Then, change Task "A" to `fetch_data("A", 4)` and see the total time increase!

---
Day 28: Asynchronous Programming \(asyncio\) \- Code & Output