RuntimeError: What It Means and How to Fix It
Error reference
RuntimeError
Language
Severity
MediumWhen it happens
RuntimeError is a catch-all exception for errors that don't fit a more specific category.
Potential fixes
To safely modify a dict during iteration, iterate over a copy (list(d.keys())) or collect changes and apply them after the loop. For other RuntimeErrors, read the message carefully as it describes the specific invalid operation.
Related errors
Deep dive
RuntimeError is a catch-all exception for errors that don't fit a more specific category. The most common instance is 'dictionary changed size during iteration', but it also covers thread-related errors and generator issues.
Why it happens
- •Adding or removing keys from a dictionary while iterating over it.
- •Calling a coroutine or generator in an invalid state.
- •Recursive call detected in a context that prohibits recursion.
- •Using a thread primitive incorrectly, such as releasing an unlocked lock.
Potential fixes
To safely modify a dict during iteration, iterate over a copy (list(d.keys())) or collect changes and apply them after the loop. For other RuntimeErrors, read the message carefully as it describes the specific invalid operation.
Examples
Code that triggers the error
d = {"a": 1, "b": 2}
for key in d:
if key == "a":
d["c"] = 3Error output
RuntimeError: dictionary changed size during iteration
Fixed code
d = {"a": 1, "b": 2}
to_add = {}
for key in d:
if key == "a":
to_add["c"] = 3
d.update(to_add)Practice in English
How would you explain a RuntimeError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free