Python Mastery – From Basics to Brilliance / Asynchronous Programming

asyncio

⚑ asyncio

asyncio is a built-in Python module used to write and run asynchronous programs.

It works mainly with async and await.


πŸ”Ή Basic Example

import asyncio

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

asyncio.run(greet())

Here:

async def   β†’ Creates a coroutine
await       β†’ Waits without blocking other async tasks
asyncio     β†’ Manages the asynchronous execution

πŸš€ Running Multiple Tasks

asyncio.gather() can run multiple coroutines concurrently.

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())
Task 1 started
Task 2 started
Task 1 finished
Task 2 finished

Both tasks can wait concurrently, instead of waiting for Task 1 to completely finish before starting Task 2.


πŸ› οΈ Common asyncio Functions

asyncio.run()       # Run an async program
asyncio.sleep()     # Pause an async task
asyncio.gather()    # Run multiple coroutines concurrently
asyncio.create_task() # Schedule a coroutine as a task

asyncio = Python's built-in framework for asynchronous programming.