Course contentsShow
← Python
Lesson 887 of 1,06014. Concurrency and PerformanceFree lesson

Running Coroutines with the Event Loop

Utilize the asyncio entry point to execute your first asynchronous program and manage the lifecycle of the loop.

Running Coroutines with the Event Loop

In this lesson, you will learn how to orchestrate the lifecycle of your asynchronous tasks using asyncio.run() to launch the event loop and execute your coroutines.

The Orchestrator of Asynchrony

Previously, we defined coroutines using async def, but calling them directly returns a coroutine object rather than executing the code inside. To actually perform the work, you need an event loop. The event loop is a scheduler that monitors your tasks, pauses them when they perform I/O, and resumes them when that I/O completes.

In modern Python, the high-level way to manage this is via asyncio.run(). This function handles the heavy lifting of:

  1. Creating a new event loop.
  2. Scheduling your main coroutine.
  3. Running the loop until the coroutine completes.
  4. Closing the loop once the task is finished.

Practical Implementation

Consider a scenario where you want to execute a non-blocking operation. Instead of manually creating or closing the loop, you define a main entry point and pass it to the runner:

import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(1)  # Simulate an I/O operation
    return "Data received"

async def main():
    result = await fetch_data()
    print(result)

# The entry point that manages the loop lifecycle
if __name__ == "__main__":
    asyncio.run(main())

When you call asyncio.run(main()), the program starts the event loop, enters the main coroutine, and pauses at the await expression. Because the loop is active, it can yield control while asyncio.sleep waits, allowing the program to remain responsive. Once the sleep finishes, the loop resumes fetch_data, retrieves the result, and finally shuts down the loop cleanly after main exits.

By using asyncio.run(), you avoid common pitfalls like leaving the event loop in a hung state or failing to close pending tasks, ensuring your asynchronous lifecycle is managed safely and predictably.

Key Takeaway: The asyncio.run() function is the standard, high-level entry point that handles the initialization, execution, and cleanup of the event loop for your asynchronous programs.