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)