]> granicus.if.org Git - python/commitdiff
Issue #24492: make sure that ``from ... import ...` raises an
authorBrett Cannon <brett@python.org>
Wed, 12 Aug 2015 01:01:31 +0000 (18:01 -0700)
committerBrett Cannon <brett@python.org>
Wed, 12 Aug 2015 01:01:31 +0000 (18:01 -0700)
ImportError if __name__ is not defined on a package.

Thanks to Armin Rigo for the bug report and diagnosing the cause.

Lib/test/test_import/__init__.py
Misc/NEWS
Python/ceval.c

index 586478ff2753bb24e1315ae2669a01306b8c57d9..14a688de1c6a7605e1ac08d4eaeb2336adfed353 100644 (file)
@@ -324,6 +324,19 @@ class ImportTests(unittest.TestCase):
         with self.assertRaisesRegex(ImportError, "^cannot import name 'bogus'"):
             from re import bogus
 
+    def test_from_import_AttributeError(self):
+        # Issue #24492: trying to import an attribute that raises an
+        # AttributeError should lead to an ImportError.
+        class AlwaysAttributeError:
+            def __getattr__(self, _):
+                raise AttributeError
+
+        module_name = 'test_from_import_AttributeError'
+        self.addCleanup(unload, module_name)
+        sys.modules[module_name] = AlwaysAttributeError()
+        with self.assertRaises(ImportError):
+            from test_from_import_AttributeError import does_not_exist
+
 
 @skip_if_dont_write_bytecode
 class FilePermissionTests(unittest.TestCase):
index 5becbfd87481d2fee8823b4e38e2c335ea4c8ae6..e7b701f87bc6d46dfc3338bdb9b1a28aa7bb3c0b 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,10 @@ Release date: 2015-08-09
 Core and Builtins
 -----------------
 
+- Issue #24492: A "package" lacking a __name__ attribute when trying to perform
+  a ``from .. import ...`` statement will trigger an ImportError instead of an
+  AttributeError.
+
 - Issue #24667: Resize odict in all cases that the underlying dict resizes.
 
 Library
index ac52ad91e212d23889ec0b8ed395aef48fd97186..8d2cdc2eda361b24e9cfe90ababe306faec0ed0b 100644 (file)
@@ -5085,19 +5085,24 @@ import_from(PyObject *v, PyObject *name)
        sys.modules. */
     PyErr_Clear();
     pkgname = _PyObject_GetAttrId(v, &PyId___name__);
-    if (pkgname == NULL)
-        return NULL;
+    if (pkgname == NULL) {
+        goto error;
+    }
     fullmodname = PyUnicode_FromFormat("%U.%U", pkgname, name);
     Py_DECREF(pkgname);
-    if (fullmodname == NULL)
+    if (fullmodname == NULL) {
         return NULL;
+    }
     x = PyDict_GetItem(PyImport_GetModuleDict(), fullmodname);
-    if (x == NULL)
-        PyErr_Format(PyExc_ImportError, "cannot import name %R", name);
-    else
-        Py_INCREF(x);
     Py_DECREF(fullmodname);
+    if (x == NULL) {
+        goto error;
+    }
+    Py_INCREF(x);
     return x;
+ error:
+    PyErr_Format(PyExc_ImportError, "cannot import name %R", name);
+    return NULL;
 }
 
 static int