Python Mastery โ€“ From Basics to Brilliance / Asynchronous Programming

Coroutlines

๐Ÿ”„ Coroutines

A coroutine is a special function that can pause its execution and resume later.

In Python, coroutines are usually created using async def.


๐Ÿ”น Creating a Coroutine

import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(2)
    print("Done")

Calling it:

greet()

does not immediately execute the function. It creates a coroutine object.

To actually run it:

asyncio.run(greet())

โธ๏ธ How await Works

async def greet():
    print("Hello")

    await asyncio.sleep(2)

    print("Done")

๐Ÿš€ Multiple Coroutines

import asyncio

async def task(name):
    print(name, "started")
    await asyncio.sleep(2)
    print(name, "finished")

async def main():
    await asyncio.gather(
        task("Task 1"),
        task("Task 2")
    )

asyncio.run(main())

Both coroutines can make progress while the other is waiting.

Coroutine = A function that can pause with await and resume later.