⏳ AsyncIO in Python
AsyncIO is a library to write concurrent code using the async/await syntax. It is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
🧠 Concepts
- Event Loop: The core of every asyncio application. It runs asynchronous tasks and callbacks, performs network IO operations, and runs subprocesses.
- Coroutines: Functions defined with
async def. - Futures/Tasks: Objects that represent the result of work that has not been completed yet.
🏃 Basic Usage
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
async def: Defines a coroutine.await: Pauses execution until the awaited object (coroutine, task, future) is done.asyncio.run(): Entry point to run the top-level entry point "main" function.
⚡ Running Tasks Concurrently
To run coroutines concurrently, wrap them in Tasks.
import asyncio
import time
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(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
🧺 Gathering Results
asyncio.gather runs awaitables concurrently and returns their results.
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
return f
async def main():
results = await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
print(results) # [2, 6, 24]
asyncio.run(main())
📝 Summary
- ✅ Single-threaded: Uses cooperative multitasking.
- ✅ Non-blocking I/O: Perfect for high-concurrency network apps.
- ✅
async/await: Native syntax for asynchronous programming. - ✅ Ecosystem: Rich ecosystem of async libraries (
aiohttp,asyncpg).
Created with ❤️ by Pynfinity