Sobes.tech
Middle

What is a coroutine?

sobes.tech AI

Answer from AI

A coroutine is a special type of function or subroutine that can suspend its execution and transfer control back to the calling code, then resume work from the same point. In Python, coroutines are implemented using the keywords async and await and are used for asynchronous programming, allowing the writing of non-blocking code.

Example of a coroutine in Python:

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)  # suspends execution for 1 second
    print("World")

asyncio.run(say_hello())

Here, say_hello is a coroutine that suspends at await asyncio.sleep(1) and resumes after the delay.