Junior — Middle
What is the role of the event loop in Python and why is it used?
sobes.tech AI
Answer from AI
The event loop in Python is a mechanism that allows asynchronous operations to be processed without blocking the main thread.
It is used in asynchronous programming, for example, with the asyncio library. The event loop monitors tasks waiting for completion (such as network requests, timers) and runs their handlers when they are ready.
The role of the event loop:
- Manage the execution of asynchronous functions and coroutines.
- Ensure non-blocking execution of input/output operations.
- Allow efficient use of resources, especially in networked and high-load applications.
Example of using the event loop with asyncio:
import asyncio
async def say_hello():
await asyncio.sleep(1)
print('Hello, world!')
async def main():
await say_hello()
asyncio.run(main())
Here, the event loop manages waiting for asyncio.sleep and executing the say_hello function without blocking the main thread.