Skip to content

Commit 7491f17

Browse files
issue #18698: ensure importlib.reload() returns the module out of sys.modules.
1 parent e76c039 commit 7491f17

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/imp.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,9 @@ def reload(module):
268268
if parent_name and parent_name not in sys.modules:
269269
msg = "parent {!r} not in sys.modules"
270270
raise ImportError(msg.format(parent_name), name=parent_name)
271-
return module.__loader__.load_module(name)
271+
module.__loader__.load_module(name)
272+
# The module may have replaced itself in sys.modules!
273+
return sys.modules[module.__name__]
272274
finally:
273275
try:
274276
del _RELOADING[name]

Lib/test/test_imp.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import shutil
66
import sys
77
from test import support
8+
from test.test_importlib import util
89
import unittest
910
import warnings
1011

@@ -285,6 +286,22 @@ def cleanup():
285286
with self.assertRaisesRegex(ImportError, 'html'):
286287
imp.reload(parser)
287288

289+
def test_module_replaced(self):
290+
# see #18698
291+
def code():
292+
module = type(sys)('top_level')
293+
module.spam = 3
294+
sys.modules['top_level'] = module
295+
mock = util.mock_modules('top_level',
296+
module_code={'top_level': code})
297+
with mock:
298+
with util.import_state(meta_path=[mock]):
299+
module = importlib.import_module('top_level')
300+
reloaded = imp.reload(module)
301+
actual = sys.modules['top_level']
302+
self.assertEqual(actual.spam, 3)
303+
self.assertEqual(reloaded.spam, 3)
304+
288305

289306
class PEP3147Tests(unittest.TestCase):
290307
"""Tests of PEP 3147."""

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ Library
202202
- Issue #17269: Workaround for socket.getaddrinfo crash on MacOS X
203203
with port None or "0" and flags AI_NUMERICSERV.
204204

205+
- Issue #18698: Ensure imp.reload() returns the module out of sys.modules.
206+
205207
- Issue #18080: When building a C extension module on OS X, if the compiler
206208
is overriden with the CC environment variable, use the new compiler as
207209
the default for linking if LDSHARED is not also overriden. This restores

0 commit comments

Comments
 (0)