0
0
PythonConceptBeginner · 4 min read

What is Event Loop in Python: Simple Explanation and Example

The event loop in Python is a programming construct that waits for and dispatches events or tasks, allowing asynchronous code to run without blocking. It manages multiple operations by running them one at a time but switching quickly between them, making programs efficient and responsive.
⚙️

How It Works

Imagine you are a chef in a kitchen who can only cook one dish at a time but wants to prepare many dishes quickly. Instead of waiting for one dish to finish completely, you start cooking one, then while it simmers, you switch to chopping vegetables for another dish, and so on. This way, you keep busy and finish all dishes faster.

The event loop in Python works similarly. It keeps track of tasks that are ready to run and runs them one by one. When a task needs to wait (like waiting for data from the internet), the event loop pauses it and switches to another task. This switching happens so fast that it feels like tasks run at the same time, even though only one runs at any moment.

This mechanism is the heart of Python's asyncio library, which helps write programs that handle many things at once without slowing down.

💻

Example

This example shows how the event loop runs two tasks that wait for different times but run without blocking each other.

python
import asyncio

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

async def main():
    task1 = asyncio.create_task(say_after(2, 'Hello after 2 seconds'))
    task2 = asyncio.create_task(say_after(1, 'Hello after 1 second'))

    print('Started tasks')
    await task2
    await task1

asyncio.run(main())
Output
Started tasks Hello after 1 second Hello after 2 seconds
🎯

When to Use

Use the event loop when you need to handle many tasks that spend time waiting, like reading files, downloading data from the internet, or talking to databases. Instead of making your program wait and freeze, the event loop lets other tasks run while some are waiting.

For example, web servers use event loops to handle many users at once without slowing down. Also, programs that work with sensors or user input can stay responsive by using an event loop.

Key Points

  • The event loop runs asynchronous tasks one at a time but switches quickly to handle many tasks efficiently.
  • It is central to Python's asyncio for writing non-blocking code.
  • It helps programs stay responsive by not waiting idly for slow operations.
  • Use it when your program needs to do many waiting tasks without freezing.

Key Takeaways

The event loop manages and runs asynchronous tasks efficiently by switching between them.
It prevents programs from freezing during slow operations like network or file access.
Python's asyncio library uses the event loop to write non-blocking code.
Use event loops for programs that handle many waiting tasks or need to stay responsive.