Python – Coroutines
Modern applications need to handle many tasks at the same time, such as:
- Web requests
- File operations
- Database queries
- Background tasks
If done one by one, programs become slow.
To solve this, Python provides Coroutines.
Coroutines allow you to write asynchronous (non-blocking) code that runs efficiently.
What is a Coroutine?
A Coroutine is a special type of function that:
Can pause execution and resume later without blocking the program.
In Python, coroutines are created using:
-
async def -
await
Why Use Coroutines?
Coroutines help you:
- Improve performance
- Handle multiple tasks at once
- Avoid blocking operations
- Build scalable applications
They are widely used in APIs, web servers, and real-time systems.
Basic Syntax
Defining a Coroutine
async def my_coroutine():
print("Hello from coroutine")
Running a Coroutine
To run it, you need an event loop:
import asyncio
async def my_coroutine():
print("Start")
await asyncio.sleep(1)
print("End")
asyncio.run(my_coroutine())
What is await?
The await keyword:
Pauses the coroutine until the task is completed.
Example:
import asyncio
async def task():
print("Task started")
await asyncio.sleep(2)
print("Task finished")
asyncio.run(task())
Running Multiple Coroutines
You can run multiple tasks concurrently.
import asyncio
async def task1():
await asyncio.sleep(2)
print("Task 1 done")
async def task2():
await asyncio.sleep(1)
print("Task 2 done")
async def main():
await asyncio.gather(task1(), task2())
asyncio.run(main())
Output:
Task 2 done
Task 1 done
(Task 2 finishes first because it sleeps less.)
Event Loop Explained
The event loop is the core of coroutines.
It:
- Schedules tasks
- Pauses and resumes coroutines
- Handles asynchronous execution
Think of it as a manager that controls all async tasks.
Real-World Example: API Calls Simulation
import asyncio
async def fetch_data(api_name, delay):
print(f"Fetching from {api_name}")
await asyncio.sleep(delay)
print(f"Done {api_name}")
async def main():
await asyncio.gather(
fetch_data("API 1", 3),
fetch_data("API 2", 1),
fetch_data("API 3", 2)
)
asyncio.run(main())
Output Behavior
Even though tasks run concurrently:
- API 2 finishes first
- API 3 next
- API 1 last
This is non-blocking execution.
Coroutines vs Threads
| Feature | Coroutines | Threads |
|---|---|---|
| Execution | Single thread | Multiple threads |
| Speed | Faster for I/O tasks | More overhead |
| Memory | Low | Higher |
| Best for | Async tasks | CPU-heavy tasks |
When to Use Coroutines
Use coroutines when:
- Making API calls
- Reading/writing files
- Handling web requests
- Building chat apps
- Processing real-time data
Advanced Concept: Task Scheduling
import asyncio
async def worker(name):
print(f"{name} started")
await asyncio.sleep(2)
print(f"{name} finished")
async def main():
task1 = asyncio.create_task(worker("A"))
task2 = asyncio.create_task(worker("B"))
await task1
await task2
asyncio.run(main())
Advantages of Coroutines
- High performance
- Non-blocking execution
- Efficient resource usage
- Scalable architecture
- Ideal for network applications
Limitations
- Not suitable for CPU-heavy tasks
- Requires async-compatible libraries
- Slight learning curve
Summary
Coroutines in Python allow asynchronous programming using async and await.
They help run multiple tasks efficiently without blocking execution, making them essential for modern applications.
They are a key feature of Python for building scalable and high-performance systems.
Conclusion
If you're building APIs, web servers, or real-time apps in Python, understanding coroutines is essential.
They make your code faster, cleaner, and capable of handling many tasks at once.


0 Comments