Coroutines are a special type of function in Python that allows concurrent execution of functions without using threads. They are an essential tool for developing efficient, scalable, and concurrent applications.
Why use Coroutines? 💡
A coroutine is a function that can pause its execution and yield control back to the caller. It can then resume its execution at a later point when it's called again.
In Python, generators are a special type of iterator that can be paused and resumed using the yield keyword. Generators are a simpler form of coroutines.
A coroutine is a function that is explicitly marked as a coroutine using the async def syntax.
async and await KeywordsThe async keyword is used to mark a function as a coroutine. The await keyword is used to pause the coroutine's execution and wait for another coroutine to complete.
Let's create a simple coroutine that generates a Fibonacci sequence.
async def fibonacci(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
await asyncio.sleep(0)
return bIn the above example, the fibonacci function is marked as a coroutine using the async def syntax. The await asyncio.sleep(0) statement is used to pause the coroutine's execution for a short duration (0 seconds).
asyncio 📝To run coroutines, you need to use the asyncio library, which provides the necessary support for managing coroutines and handling concurrent tasks.
import asyncio
async def main():
print("Fibonacci of 5: ", await fibonacci(5))
print("Fibonacci of 10: ", await fibonacci(10))
if __name__ == "__main__":
asyncio.run(main())In the above example, we have a main function that runs two instances of the fibonacci coroutine concurrently using the await keyword. The asyncio.run(main()) statement is used to start the event loop and run the coroutines.
What is the main advantage of using coroutines over threads?
What is a generator in Python?