Multiple coroutines are executed concurrently with asyncio.gather.
5. Using async with Loops
Coroutines can be used inside loops with await.
6. Combining Coroutines and Exception Handling
Coroutines can include try/except blocks for exception handling.
7. Coroutine with Timeout
asyncio.wait_for can enforce a timeout for a coroutine.
8. Creating a Coroutine Dynamically
Dynamically creates coroutines in a list and runs them concurrently.
9. Using await in a Coroutine Chain
Data is passed between coroutines using await.
10. Coroutine with Infinite Loop
An infinite coroutine can be created and later canceled.
These snippets demonstrate the power of async and await for coroutine-based asynchronous programming in Python. They illustrate the ability to handle concurrent tasks, manage timeouts, pass data, and handle exceptions in a clean and readable way.
import asyncio
async def dynamic_task(name):
print(f"Task {name} is running.")
await asyncio.sleep(2)
print(f"Task {name} is done.")
tasks = [dynamic_task(i) for i in range(3)]
asyncio.run(asyncio.gather(*tasks))