Skip to content

Commit 3d1ca86

Browse files
authored
bpo-45353: Remind sys.modules users to copy when iterating. (GH-28842)
This is true of all dictionaries in Python, but this one tends to catch people off guard as they don't realize when sys.modules might change out from underneath them as a hidden side effect of their code. Copying it first avoids the RuntimeError. An example when this happens in single threaded code are codecs being loaded which are an implicit time of use import that most need not think about.
1 parent 5b4a767 commit 3d1ca86

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

Doc/library/sys.rst

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1073,7 +1073,11 @@ always available.
10731073
This is a dictionary that maps module names to modules which have already been
10741074
loaded. This can be manipulated to force reloading of modules and other tricks.
10751075
However, replacing the dictionary will not necessarily work as expected and
1076-
deleting essential items from the dictionary may cause Python to fail.
1076+
deleting essential items from the dictionary may cause Python to fail. If
1077+
you want to iterate over this global dictionary always use
1078+
``sys.modules.copy()`` or ``tuple(sys.modules)`` to avoid exceptions as its
1079+
size may change during iteration as a side effect of code or activity in
1080+
other threads.
10771081

10781082

10791083
.. data:: orig_argv

0 commit comments

Comments
 (0)