Fundamentals 6 min read

Understanding async and await in Python with Practical Examples

This article introduces Python's async and await keywords, explains how they enable coroutine programming, and provides multiple practical examples including simple coroutine definitions, awaiting tasks, concurrent execution with asyncio.gather, HTTP requests using aiohttp, and resource management with custom coroutine-based managers.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding async and await in Python with Practical Examples

This article introduces Python's async and await keywords, which enable coroutine programming for asynchronous operations.

async keyword defines a coroutine function. Example:

import asyncio
async def hello_world():
    print("Hello, World!")
# 创建一个事件循环并运行协程
asyncio.run(hello_world())

await keyword suspends the coroutine until another coroutine or async operation completes. Example:

import asyncio
async def sleep_and_print(delay, message):
    await asyncio.sleep(delay)
    print(message)
async def main():
    print(f"Started at {time.strftime('%X')}")
    await sleep_and_print(1, "Hello")
    await sleep_and_print(2, "World")
    print(f"Finished at {time.strftime('%X')}")
# 创建一个事件循环并运行协程
asyncio.run(main())

To run multiple coroutines concurrently, asyncio.gather can combine them. Example:

import asyncio
async def sleep_and_print(delay, message):
    await asyncio.sleep(delay)
    print(message)
async def main():
    print(f"Started at {time.strftime('%X')}")
    task1 = asyncio.create_task(sleep_and_print(1, "Hello"))
    task2 = asyncio.create_task(sleep_and_print(2, "World"))
    await asyncio.gather(task1, task2)
    print(f"Finished at {time.strftime('%X')}")
# 创建一个事件循环并运行协程
asyncio.run(main())

For asynchronous HTTP requests, the aiohttp library can be used. Example:

import asyncio
import aiohttp
async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()
async def main():
    urls = [
        "https://api.example.com/data1",
        "https://api.example.com/data2",
        "https://api.example.com/data3"
    ]
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)
    for response in responses:
        print(response)
# 创建一个事件循环并运行协程
asyncio.run(main())

A more advanced example shows how coroutines can manage resources via a custom ResourceManager class. Example:

import asyncio
class ResourceManager:
    def __init__(self):
        self.resources = {}
    async def acquire(self, resource_id):
        await asyncio.sleep(1)  # 模拟资源获取时间
        print(f"Acquired resource {resource_id}")
        self.resources[resource_id] = True
    async def release(self, resource_id):
        await asyncio.sleep(1)  # 模拟资源释放时间
        print(f"Released resource {resource_id}")
        del self.resources[resource_id]
async def use_resource(manager, resource_id):
    await manager.acquire(resource_id)
    print(f"Using resource {resource_id}")
    await asyncio.sleep(2)  # 模拟使用时间
    await manager.release(resource_id)
    print(f"Released resource {resource_id}")
async def main():
    manager = ResourceManager()
    tasks = [use_resource(manager, i) for i in range(5)]
    await asyncio.gather(*tasks)
# 创建一个事件循环并运行协程
asyncio.run(main())

In summary, async defines coroutine functions, await pauses execution until completion, asyncio.gather enables concurrent coroutines, aiohttp facilitates asynchronous HTTP requests, and coroutines can be used for resource management.

ConcurrencyAsynccoroutineAsyncIOawait
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.