Junior — Middle
Explain how the asyncio library works for asynchronous programming in Python.
sobes.tech AI
Answer from AI
The asyncio library in Python implements an asynchronous programming model based on an event loop. It allows writing non-blocking code that can perform multiple I/O operations concurrently without creating multiple threads.
Main components and principles:
- Event Loop — the central loop that manages task execution and event handling.
- Coroutine functions (declared with
async def) — functions that can suspend their execution usingawait, allowing other tasks to run in the meantime. - Futures and Tasks — objects representing deferred operations.
Example:
import asyncio
async def fetch_data():
print('Start fetching')
await asyncio.sleep(1) # simulate an asynchronous operation
print('Done fetching')
return {'data': 123}
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
In this example, asyncio.run starts the event loop, which executes the main coroutine. Inside main, fetch_data is called, which suspends at await asyncio.sleep(1), allowing the event loop to switch to other tasks (if any). This efficiently utilizes resources, especially when working with network operations or I/O.