Junior — Middle
Can you explain the concept of coroutines in Python and their usage?
sobes.tech AI
Answer from AI
Coroutines in Python are functions that can suspend their execution and resume later, allowing for asynchronous code that does not block the thread. They are used for efficient management of input/output and concurrency without creating multiple threads.
Main points:
- Coroutines are declared with
async def. - To call a coroutine,
awaitis used, which suspends execution until the result is available. - They enable writing code that appears synchronous but operates asynchronously.
Example:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # simulate an asynchronous operation
print("World")
asyncio.run(say_hello())
In this example, asyncio.sleep does not block the thread but suspends the coroutine for 1 second, allowing other tasks to run.