92. Coroutines in Python
Here are 10 Python code snippets to demonstrate the use of coroutines in Python with async and await:
1. Basic Coroutine Example
import asyncio
async def greet():
print("Hello, coroutine!")
await asyncio.sleep(1)
print("Goodbye, coroutine!")
asyncio.run(greet())Defines a coroutine using async and await, and executes it with asyncio.run.
2. Chaining Coroutines
import asyncio
async def step1():
print("Step 1 completed.")
await asyncio.sleep(1)
async def step2():
print("Step 2 completed.")
await asyncio.sleep(1)
async def main():
await step1()
await step2()
asyncio.run(main())Coroutines can be chained together using await.
3. Returning Values from Coroutines
A coroutine can return a value after an await.
4. Running Coroutines Concurrently
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.
Last updated