10000 bpo-13487: Use sys.modules.copy() in inspect.getmodule() for thread s… · python/cpython@6b452ff · GitHub
[go: up one dir, main page]

Skip to content

Commit 6b452ff

Browse files
bpo-13487: Use sys.modules.copy() in inspect.getmodule() for thread safety. (GH-18786)
`list(sys.modules.items())` was apparently not immune to "dictionary changed size during iteration" errors. Tested internally using an integration test that has run into this a couple of times in the past two years. With this patch applied, the test is no longer flaky. (cherry picked from commit 85cf1d5) Co-authored-by: Gregory P. Smith <gps@google.com>
1 parent 5a3926d commit 6b452ff

File tree

2 files changed

+4
-1
lines changed

2 files changed

+4
-1
lines changed

Lib/inspect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -741,7 +741,7 @@ def getmodule(object, _filename=None):
741741
return sys.modules.get(modulesbyfile[file])
742742
# Update the filename to module name cache and check yet again
743743
# Copy sys.modules in order to cope with changes while iterating
744-
for modname, module in list(sys.modules.items()):
744+
for modname, module in sys.modules.copy().items():
745745
if ismodule(module) and hasattr(module, '__file__'):
746746
f = module.__file__
747747
if f == _filesbymodname.get(modname, None):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Avoid a possible *"RuntimeError: dictionary changed size during iteration"*
2+
from :func:`inspect.getmodule` when it tried to loop through
3+
:attr:`sys.modules`.

0 commit comments

Comments
 (0)
0