[Python-checkins] cpython (2.7): Issue #15578: Correctly incref the parent module while importing.

eric.snow python-checkins at python.org
Wed Sep 7 22:09:01 EDT 2016


https://hg.python.org/cpython/rev/2d6dd8402d77
changeset:   103288:2d6dd8402d77
branch:      2.7
parent:      103278:26397c1ea557
user:        Eric Snow <ericsnowcurrently at gmail.com>
date:        Wed Sep 07 19:08:02 2016 -0700
summary:
  Issue #15578: Correctly incref the parent module while importing.

files:
  Lib/test/test_import.py |  18 ++++++++++++++++++
  Misc/NEWS               |   2 ++
  Python/import.c         |   2 ++
  3 files changed, 22 insertions(+), 0 deletions(-)


diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -397,6 +397,24 @@
         finally:
             sys.path.pop(0)
 
+    def test_replace_parent_in_sys_modules(self):
+        dir_name = os.path.abspath(TESTFN)
+        os.mkdir(dir_name)
+        try:
+            pkg_dir = os.path.join(dir_name, 'sa')
+            os.mkdir(pkg_dir)
+            with open(os.path.join(pkg_dir, '__init__.py'), 'w') as init_file:
+                init_file.write("import v1")
+            with open(os.path.join(pkg_dir, 'v1.py'), 'w') as v1_file:
+                v1_file.write("import sys;"
+                              "sys.modules['sa'] = sys.modules[__name__];"
+                              "import sa")
+            sys.path.insert(0, dir_name)
+            # a segfault means the test failed!
+            import sa
+        finally:
+            rmtree(dir_name)
+
 
 class PycRewritingTests(unittest.TestCase):
     # Test that the `co_filename` attribute on code objects always points
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -7082,6 +7082,8 @@
 
 - Add Py3k warnings for parameter names in parentheses.
 
+- Issue #15578: Correctly incref the parent module while importing.
+
 - Issue #7362: Give a proper error message for ``def f((x)=3): pass``.
 
 - Issue #7085: Fix crash when importing some extensions in a thread on MacOSX
diff --git a/Python/import.c b/Python/import.c
--- a/Python/import.c
+++ b/Python/import.c
@@ -2243,8 +2243,10 @@
     if (parent == NULL)
         goto error_exit;
 
+    Py_INCREF(parent);
     head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
                         &buflen);
+    Py_DECREF(parent);
     if (head == NULL)
         goto error_exit;
 

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list