Skip to content

How to Fix Event Loop Already Running Error in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Event Loop Already Running Error in Python. We cover key concepts, practical examples, and best practices.

Python raises RuntimeError: asyncio.run() cannot be called from a running event loop when you try to start a new event loop while one is already active.

The Wrong Way

import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return "data"

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

# Works
asyncio.run(main())

# Fails -- another async context calls asyncio.run again
async def wrapper():
    asyncio.run(main())  # RuntimeError

This produces:

RuntimeError: asyncio.run() cannot be called from a running event loop

The Right Way

Use await directly instead of asyncio.run() inside async contexts:

import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return "data"

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

async def wrapper():
    await main()  # use await, not asyncio.run

asyncio.run(wrapper())

Output:

data

Step-by-Step Fix

1. Never nest asyncio.run()

# Wrong
async def inner():
    await asyncio.sleep(1)

def outer():
    asyncio.run(inner())  # OK in sync code

async def bad():
    asyncio.run(inner())  # RuntimeError -- event loop running

# Right
async def good():
    await inner()  # use await inside async functions

2. Use the running loop if needed

import asyncio

async def run_sync_in_async():
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, sync_function)
    return result

3. Check if an event loop is running

import asyncio

def safe_run(coro):
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if loop and loop.is_running():
        return asyncio.ensure_future(coro)
    else:
        return asyncio.run(coro)

4. Use nest_asyncio for notebooks and nested loops

pip install nest_asyncio
import nest_asyncio
nest_asyncio.apply()

Prevention Tips

  • Use await inside async functions, never asyncio.run().
  • Keep asyncio.run() as a single call at the program's entry point.
  • Use asyncio.get_running_loop() inside async functions.
  • Use loop.run_in_executor() for blocking sync code.
  • Use nest_asyncio only as a last resort for interactive environments.

Common Mistakes with event loop

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why can I not nest asyncio.run()?

asyncio.run() creates a new event loop and sets it as the current loop. If a loop is already running, this would create conflicting loop states. Python prevents this to protect event loop integrity.

How do I run async code in a Jupyter notebook?

Jupyter already runs an event loop. Use await coroutine() directly in notebook cells without asyncio.run(). Install nest_asyncio if you need to call asyncio.run() explicitly.

What is the difference between get_event_loop and get_running_loop?

get_event_loop() returns the current event loop or creates one if none exists. get_running_loop() raises RuntimeError if no loop is running. Prefer get_running_loop() inside async code.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro