Getting Started with Python's asyncio ⚡

Asyncio icon

Getting Started with Python's asyncio ⚡

asyncio is Python’s powerful library for asynchronous programming, enabling efficient handling of network I/O, file operations, and timing-related tasks.

1. Writing Basic Async Functions

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(say_hello())

2. Executing Multiple Tasks Concurrently

import asyncio

async def worker(name, delay):
    await asyncio.sleep(delay)
    print(f"{name} completed after {delay} seconds")

async def main():
    tasks = [
        worker("Task A", 1),
        worker("Task B", 2),
        worker("Task C", 1.5)
    ]
    await asyncio.gather(*tasks)

asyncio.run(main())

3. Network I/O Example with aiohttp

import asyncio
import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            print(url, resp.status)
            return await resp.text()

async def main():
    urls = ["https://example.com", "https://httpbin.org/get"]
    results = await asyncio.gather(*(fetch(u) for u in urls))
    print("All requests complete")

asyncio.run(main())

4. Repetitive Tasks with Timers

import asyncio

async def ticker(interval, count):
    for i in range(count):
        print(f"Tick: {i}")
        await asyncio.sleep(interval)

asyncio.run(ticker(0.5, 5))

Summary

  • Define and execute asynchronous functions using async/await.
  • Run multiple tasks concurrently with asyncio.gather().
  • Handle network operations asynchronously using aiohttp.
  • Use asyncio.sleep() for timers and repeated tasks.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“