πŸ”§ Error Fixes
Β· 1 min read

Python RuntimeError β€” How to Fix It


RuntimeError: dictionary changed size during iteration
RuntimeError: Event loop is already running
RuntimeError: maximum recursion depth exceeded

A RuntimeError means something went wrong that doesn’t fit other error categories. The message tells you what.

Fix 1: Dictionary Changed Size During Iteration

# ❌ Modifying dict while iterating
for key in my_dict:
    if my_dict[key] == 0:
        del my_dict[key]  # πŸ’₯

# βœ… Iterate over a copy
for key in list(my_dict.keys()):
    if my_dict[key] == 0:
        del my_dict[key]

# βœ… Or use dict comprehension
my_dict = {k: v for k, v in my_dict.items() if v != 0}

Fix 2: Set Changed Size During Iteration

# ❌ Same issue with sets
for item in my_set:
    my_set.discard(item)  # πŸ’₯

# βœ… Iterate over a copy
for item in list(my_set):
    my_set.discard(item)

Fix 3: Event Loop Already Running (asyncio)

# ❌ Calling asyncio.run() inside Jupyter or an existing loop
asyncio.run(my_coroutine())  # πŸ’₯ Loop already running

# βœ… In Jupyter, use await directly
await my_coroutine()

# βœ… Or use nest_asyncio
import nest_asyncio
nest_asyncio.apply()
asyncio.run(my_coroutine())

Fix 4: Generator Already Executing

# ❌ Calling next() on a generator from within itself
def gen():
    yield 1
    next(g)  # πŸ’₯ Can't re-enter generator

g = gen()
next(g)

# βœ… Don't call next() on a generator from within itself

Fix 5: Thread Safety

# ❌ Modifying shared data from multiple threads
# βœ… Use threading.Lock
import threading
lock = threading.Lock()

with lock:
    shared_data.append(item)
πŸ“˜