]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-128030: Avoid error from PyModule_GetFilenameObject for non-module (#128047)
authorShantanu <12621235+hauntsaninja@users.noreply.github.com>
Fri, 20 Dec 2024 08:22:26 +0000 (00:22 -0800)
committerGitHub <noreply@github.com>
Fri, 20 Dec 2024 08:22:26 +0000 (00:22 -0800)
I missed the extra `PyModule_Check` in #127660 because I was looking at
3.12 as the base implementation for import from. This meant that I
missed the `PyModuleCheck` introduced in #112661.

Lib/test/test_import/__init__.py
Misc/NEWS.d/next/Core_and_Builtins/2024-12-17-22-28-15.gh-issue-128030.H1ptOD.rst [new file with mode: 0644]
Python/ceval.c

index 83efbc1e25e77af3c2b968f64d7e6a259e825e49..c2cec6444cb43ac5d73e1680e4ae1f73bc1e7c6f 100644 (file)
@@ -851,6 +851,29 @@ from os import this_will_never_exist
                 stdout, stderr = popen.communicate()
                 self.assertIn(expected_error, stdout)
 
+    def test_non_module_from_import_error(self):
+        prefix = """
+import sys
+class NotAModule: ...
+nm = NotAModule()
+nm.symbol = 123
+sys.modules["not_a_module"] = nm
+from not_a_module import symbol
+"""
+        scripts = [
+            prefix + "from not_a_module import missing_symbol",
+            prefix + "nm.__spec__ = []\nfrom not_a_module import missing_symbol",
+        ]
+        for script in scripts:
+            with self.subTest(script=script):
+                expected_error = (
+                    b"ImportError: cannot import name 'missing_symbol' from "
+                    b"'<unknown module name>' (unknown location)"
+                )
+            popen = script_helper.spawn_python("-c", script)
+            stdout, stderr = popen.communicate()
+            self.assertIn(expected_error, stdout)
+
     def test_script_shadowing_stdlib(self):
         script_errors = [
             (
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-12-17-22-28-15.gh-issue-128030.H1ptOD.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-17-22-28-15.gh-issue-128030.H1ptOD.rst
new file mode 100644 (file)
index 0000000..93d7863
--- /dev/null
@@ -0,0 +1 @@
+Avoid error from calling ``PyModule_GetFilenameObject`` on a non-module object when importing a non-existent symbol from a non-module object.
index fd891d7839151e374c5ebc411a25baa138980d5d..bfdf5687c287db26c9de4ae6c869c559ea03ce88 100644 (file)
@@ -2860,7 +2860,7 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
         }
     }
 
-    if (origin == NULL) {
+    if (origin == NULL && PyModule_Check(v)) {
         // Fall back to __file__ for diagnostics if we don't have
         // an origin that is a location
         origin = PyModule_GetFilenameObject(v);