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
Copy
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
Copy
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
Copy
A coroutine can return a value after an await.
4. Running Coroutines Concurrently
Copy
Multiple coroutines are executed concurrently with asyncio.gather.
5. Using async with Loops
Copy
Coroutines can be used inside loops with await.
6. Combining Coroutines and Exception Handling
Copy
Coroutines can include try/except blocks for exception handling.
7. Coroutine with Timeout
Copy
asyncio.wait_for can enforce a timeout for a coroutine.
8. Creating a Coroutine Dynamically
Copy
Dynamically creates coroutines in a list and runs them concurrently.
9. Using await in a Coroutine Chain
Copy
Data is passed between coroutines using await.
10. Coroutine with Infinite Loop
Copy
An infinite coroutine can be created and later canceled.
Last updated