Understanding Coroutines

Definition and Examples

Coroutines are functions defined with the async def keyword that allow for asynchronous execution. They use the await keyword to pause execution until the awaited task completes, enabling other tasks to run concurrently.

import asyncio

async def example_coroutine():
    print("Coroutine started")
    await asyncio.sleep(1)
    print("Coroutine resumed")

asyncio.run(example_coroutine())

Coroutine Functions vs Regular Functions

Coroutine functions differ from regular functions in that they can be paused and resumed, allowing other tasks to run concurrently. Regular functions execute synchronously, blocking the execution flow until they complete.

The Await Expression

The await expression is used to pause the execution of a coroutine until the awaited task completes. It allows for non-blocking execution, enabling other tasks to run concurrently while waiting for an I/O operation or another coroutine to complete.

import asyncio

async def fetch_data():
    await asyncio.sleep(2)
    return "Data fetched"

async def main():
    data = await fetch_data()
    print(data)

asyncio.run(main())