Files
the_information_nexus/tech_docs/python/asyncio.md
2024-05-01 12:28:44 -06:00

2.9 KiB

For asynchronous programming in Python, asyncio stands out as a vital library. It provides a framework that revolves around writing concurrent code using the async/await syntax introduced in Python 3.5. asyncio is used for developing server-side applications, database connection libraries, and speed enhancements in web frameworks. Here's a concise reference guide for common use cases with asyncio, aiding in understanding and implementing asynchronous programming:

asyncio Reference Guide

Installation

asyncio is included in the standard library of Python 3.5 and later, so no additional installation is necessary.

Basic Usage

Importing asyncio

import asyncio

Running an Async Function

async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')

# Python 3.7+
asyncio.run(main())

Creating Tasks

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))

    print('Started tasks')
    # Wait until both tasks are completed
    await task1
    await task2

asyncio.run(main())

Waiting with asyncio.gather

async def main():
    # Schedule three calls concurrently
    await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world'),
        say_after(3, '!')
    )

asyncio.run(main())

Working with I/O Operations

Using asyncio for Asynchronous I/O

asyncio provides support for asynchronous I/O operations, such as reading and writing to files, network requests, and database operations, using the aiohttp library for HTTP requests, for example.

Example: Asynchronous HTTP Requests

import aiohttp

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    html = await fetch('http://python.org')
    print(html[:100])

asyncio.run(main())

Event Loop

Understanding the Event Loop

The event loop is the core of asyncio applications, handling execution of asynchronous tasks, callbacks, and I/O events. Use asyncio.run() to run the top-level entry point “main()” function.

Managing the Event Loop Manually

For fine-grained control over the event loop, you can manage it manually, which is more common in complex applications and libraries.

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()

asyncio makes it easier to write and manage asynchronous code, facilitating the development of efficient and scalable applications, especially for I/O-bound and high-level structured network code. It's a powerful tool in the Python standard library, enabling developers to leverage asynchronous programming patterns for improved performance.