]> granicus.if.org Git - python/commitdiff
issue #18698: ensure importlib.reload() returns the module out of sys.modules.
authorEric Snow <ericsnowcurrently@gmail.com>
Thu, 15 Aug 2013 00:03:34 +0000 (18:03 -0600)
committerEric Snow <ericsnowcurrently@gmail.com>
Thu, 15 Aug 2013 00:03:34 +0000 (18:03 -0600)
Lib/imp.py
Lib/test/test_imp.py
Misc/NEWS

index 34b6c542e1203fdcd8e99163af2ff067d3474363..30c343f62e0d88d42c647b6bbd323bbf56301d82 100644 (file)
@@ -268,7 +268,9 @@ def reload(module):
         if parent_name and parent_name not in sys.modules:
             msg = "parent {!r} not in sys.modules"
             raise ImportError(msg.format(parent_name), name=parent_name)
-        return module.__loader__.load_module(name)
+        module.__loader__.load_module(name)
+        # The module may have replaced itself in sys.modules!
+        return sys.modules[module.__name__]
     finally:
         try:
             del _RELOADING[name]
index 3fb119bfc3fdaf7023bf70a8af22052a37b4d4a3..bf29e424d24a52104e76dd13ea5f70d870392d54 100644 (file)
@@ -5,6 +5,7 @@ import os.path
 import shutil
 import sys
 from test import support
+from test.test_importlib import util
 import unittest
 import warnings
 
@@ -285,6 +286,22 @@ class ReloadTests(unittest.TestCase):
         with self.assertRaisesRegex(ImportError, 'html'):
             imp.reload(parser)
 
+    def test_module_replaced(self):
+        # see #18698
+        def code():
+            module = type(sys)('top_level')
+            module.spam = 3
+            sys.modules['top_level'] = module
+        mock = util.mock_modules('top_level',
+                                 module_code={'top_level': code})
+        with mock:
+            with util.import_state(meta_path=[mock]):
+                module = importlib.import_module('top_level')
+                reloaded = imp.reload(module)
+                actual = sys.modules['top_level']
+                self.assertEqual(actual.spam, 3)
+                self.assertEqual(reloaded.spam, 3)
+
 
 class PEP3147Tests(unittest.TestCase):
     """Tests of PEP 3147."""
index 7a4491aa3a8df3b337e752c0a3fa3c5f1b0a65c6..0dd2d1099ba4bbe198fe5cd8546921ba32d53c75 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -202,6 +202,8 @@ Library
 - Issue #17269: Workaround for socket.getaddrinfo crash on MacOS X
   with port None or "0" and flags AI_NUMERICSERV.
 
+- Issue #18698: Ensure imp.reload() returns the module out of sys.modules.
+
 - Issue #18080: When building a C extension module on OS X, if the compiler
   is overriden with the CC environment variable, use the new compiler as
   the default for linking if LDSHARED is not also overriden.  This restores