Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8e45540

Browse files
Closes issue #18698: ensure importlib.reload() returns the module out of sys.modules.
1 parent 01dbca0 commit 8e45540

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

Lib/importlib/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ def reload(module):
118118
if parent_name and parent_name not in sys.modules:
119119
msg = "parent {!r} not in sys.modules"
120120
raise ImportError(msg.format(parent_name), name=parent_name)
121-
return module.__loader__.load_module(name)
121+
module.__loader__.load_module(name)
122+
# The module may have replaced itself in sys.modules!
123+
return sys.modules[module.__name__]
122124
finally:
123125
try:
124126
del _RELOADING[name]

Lib/test/test_importlib/test_api.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,22 @@ def test_reload_modules(self):
162162
module = importlib.import_module(mod)
163163
importlib.reload(module)
164164

165+
def test_module_replaced(self):
166+
def code():
167+
import sys
168+
module = type(sys)('top_level')
169+
module.spam = 3
170+
sys.modules['top_level'] = module
171+
mock = util.mock_modules('top_level',
172+
module_code={'top_level': code})
173+
with mock:
174+
with util.import_state(meta_path=[mock]):
175+
module = importlib.import_module('top_level')
176+
reloaded = importlib.reload(module)
177+
actual = sys.modules['top_level']
178+
self.assertEqual(actual.spam, 3)
179+
self.assertEqual(reloaded.spam, 3)
180+
165181

166182
class InvalidateCacheTests(unittest.TestCase):
167183

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,8 @@ Core and Builtins
203203

204204
- Issue #17867: Raise an ImportError if __import__ is not found in __builtins__.
205205

206+
- Issue #18698: Ensure importlib.reload() returns the module out of sys.modules.
207+
206208
- Issue #17857: Prevent build failures with pre-3.5.0 versions of sqlite3,
207209
such as was shipped with Centos 5 and Mac OS X 10.4.
208210

0 commit comments

Comments
 (0)