[Fixed 2026] RuntimeError: Event Loop Is Closed

As a developer, you may often encounter one of the common errors which is Runtimeerror: event loop is closed .

However, don’t worry! In this article, we will provide you with the best possible solution to this error.

Also, we’ll discuss what causes it, how to fix it, and provide some frequently asked questions(FAQs).

Why we get this runtimeerror event loop is closed?

We get this runtimeerror event loop is closed error usually occurs because when we attempt to run an operation on a closed event loop.

An event loop is in charge of running the coroutines in an asyncio application. If the event loop is closed, any coroutines that are still running will raise this error.

Reasons for this Error

There are some reasons why an event loop might be closed. One of the common reasons is that the application has already completed its work and has closed the event loop.

Another reason could be that an exception was raised in a coroutine, causing the event loop to be closed.

How to Fix the Python Runtimeerror Event Loop is Closed Error?

Now that we learned what reasons for this error, let’s discuss how to fix it. There are a few different solutions you can use to fix the “Python RuntimeError Event Loop is Closed” error, it depends upon what’s causing the error.

Solution 1: Use a try/except block

One way to fix the error is to use a try/except block to catch the error and handle it gracefully.

Here’s an example:

import asyncio

async def my_coroutine():
    # some code here

try:
    asyncio.run(my_coroutine())
except RuntimeError as e:
    if "Event loop is closed" in str(e):
        pass # do something here, like log the error

In this example, we are using the asyncio.run() function to run our coroutine. If the coroutine raises a “RuntimeError Event Loop is Closed” error, we catch it in a try/except block and handle it carefully.

Solution 2: Use a context manager

Another solution to fix the error is to use a context manager, and make sure that the event loop is accurately closed when your application is finished.

Here’s an example:

import asyncio

async def my_coroutine():
    # some code here

async def main():
    async with asyncio.get_event_loop() as loop:
        await loop.create_task(my_coroutine())

if __name__ == "__main__":
    asyncio.run(main())

In this example, we are using a context manager to build and manage our event loop. When our application is finished, the context manager ensures that the event loop is accurately closed.

Solution 3: Avoid using the event loop directly

Finally, another solution to prevent the error is to avoid using the event loop directly. Instead, use the high-level asyncio functions and methods provided by the asyncio library.

For example:

Instead of using loop.run_until_complete(), use asyncio.run(). This is to make sure that the event loop is properly closed when your application is finished.

For example:

import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

async def process_data():
    urls = ['https://api.example.com/data/1', 'https://api.example.com/data/2', 'https://api.example.com/data/3']
    tasks = []
    for url in urls:
        task = asyncio.create_task(fetch_data(url))
        tasks.append(task)
    results = await asyncio.gather(*tasks)
    for data in results:
        # process the data
        pass

async def main():
    await process_data()

asyncio.run(main())

Here, we define a main() coroutine that calls process_data() and use the asyncio.run() function to execute it. This is to make sure that the event loop is properly created and closed, and avoids the “Event loop is closed” error.

Additional Resources

Here are some additional resources for the following error messages:

asyncio RuntimeError patterns

asyncio RuntimeErrors come from misusing the event loop: calling await outside async context, running loops that already exist, or mixing sync and async in the wrong order.

Common triggers

  • No running event loop. asyncio.get_event_loop() was deprecated. Use asyncio.get_running_loop() inside async, or asyncio.run() to start.
  • Loop already running. In Jupyter, an event loop already exists. Use await at top level, do not call asyncio.run.
  • Coroutine was never awaited. coro() creates a coroutine object; must await coro().
  • Concurrent I/O without gather. await is sequential; use asyncio.gather() or TaskGroup for concurrency.

Diagnostic pattern

import asyncio

# BAD — no event loop
async def fetch():
    await asyncio.sleep(1)
    return "done"

result = fetch()  # RuntimeWarning: coroutine was never awaited

# GOOD — asyncio.run wraps the event loop
result = asyncio.run(fetch())

# Modern Python 3.11+ TaskGroup for concurrent tasks
async def main():
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(fetch_url("a"))
        t2 = tg.create_task(fetch_url("b"))
    return t1.result(), t2.result()

asyncio.run(main())

Best practices

  • Wrap top-level with asyncio.run. Standard entry point.
  • Use TaskGroup (3.11+) for concurrent tasks with automatic error propagation.
  • Use anyio for cross-runtime async code (asyncio + trio).
  • In Jupyter, await at cell top level — the notebook manages the loop.

Frequently Asked Questions

What is Python RuntimeError and what causes it?

RuntimeError is a generic catch-all for errors that don’t fit other specific categories. Common 2026 sources: PyTorch CUDA out of memory, asyncio event-loop conflicts, Flask ‘working outside of application context,’ mutating a dict/list during iteration, and threading deadlocks. The error message usually points to the underlying cause.

How do I fix PyTorch CUDA out of memory RuntimeError?

Three options: (1) Reduce batch size (the most direct fix). (2) Clear cache: torch.cuda.empty_cache() between epochs. (3) Use mixed precision (torch.cuda.amp.autocast) to halve memory. (4) If on a shared GPU, check nvidia-smi to see other processes hogging memory.

How do I fix ‘dictionary changed size during iteration’?

You’re modifying a dict (adding/removing keys) inside ‘for k in my_dict’. Two fixes: (1) iterate over a copy: for k in list(my_dict.keys()). (2) Build a new dict and assign: my_dict = {k: v for k, v in my_dict.items() if keep(k)}. Same applies to set and list mutations during iteration.

How do I fix Flask ‘Working outside of application context’?

Wrap the code in app.app_context(): with app.app_context(): db.create_all(). This usually happens in scripts run outside of a Flask request (CLI tools, background jobs). For test code, use the test client which auto-creates context.

Where can I find more RuntimeError fixes?

Browse the RuntimeError reference hub for 49+ specific fixes (PyTorch CUDA, asyncio, Flask context, dict iteration). For Python fundamentals see the Python Tutorial hub.

Conclusion

In conclusion, the “RuntimeError: Event Loop is Closed” error is a common issue which typically occurs when writing asynchronous code in Python.

However, by knowing the root causes and applying the correct solutions, you can avoid or fix this error and ensure that your code runs smoothly.

FAQs

What is a runtime error?

A runtime error is an error that occurs during the execution of a program, rather than during its compilation or build.

How do I know if an event loop is closed?

You can check if an event loop is closed by calling the is_closed() method of the loop object.

Why does the runtimeerror event loop is closed error occur?

The runtimeerror event loop is closed error that occurs because a Python program attempts to access a closed event loop.

What is an event loop in Python?

An event loop is a design in Python that handles the scheduling of different events and callbacks. It is used to manage asynchronous operations in Python programs.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →