Skip to content

Commit 256e3c3

Browse files
committed
pythongh-128030: Avoid error from PyModule_GetFilenameObject for non-module
I missed the extra `PyModule_Check` in python#127660 because I was looking at 3.12 as the base implementation for import from. This meant that I missed the `PyModuleCheck` introduced in python#112661.
1 parent be8ae08 commit 256e3c3

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

Lib/test/test_import/__init__.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,29 @@ def test_frozen_module_from_import_error(self):
851851
stdout, stderr = popen.communicate()
852852
self.assertIn(expected_error, stdout)
853853

854+
def test_non_module_from_import_error(self):
855+
prefix = """
856+
import sys
857+
class NotAModule: ...
858+
nm = NotAModule()
859+
nm.symbol = 123
860+
sys.modules["not_a_module"] = nm
861+
from not_a_module import symbol
862+
"""
863+
scripts = [
864+
prefix + "from not_a_module import missing_symbol",
865+
prefix + "nm.__spec__ = []\nfrom not_a_module import missing_symbol",
866+
]
867+
for script in scripts:
868+
with self.subTest(script=script):
869+
expected_error = (
870+
b"ImportError: cannot import name 'missing_symbol' from "
871+
b"'<unknown module name>' (unknown location)"
872+
)
873+
popen = script_helper.spawn_python("-c", script)
874+
stdout, stderr = popen.communicate()
875+
self.assertIn(expected_error, stdout)
876+
854877
def test_script_shadowing_stdlib(self):
855878
script_errors = [
856879
(

Python/ceval.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2863,13 +2863,15 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
28632863
if (origin == NULL) {
28642864
// Fall back to __file__ for diagnostics if we don't have
28652865
// an origin that is a location
2866-
origin = PyModule_GetFilenameObject(v);
2867-
if (origin == NULL) {
2868-
if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
2869-
goto done;
2866+
if (PyModule_Check(v)) {
2867+
origin = PyModule_GetFilenameObject(v);
2868+
if (origin == NULL) {
2869+
if (!PyErr_ExceptionMatches(PyExc_SystemError)) {
2870+
goto done;
2871+
}
2872+
// PyModule_GetFilenameObject raised "module filename missing"
2873+
_PyErr_Clear(tstate);
28702874
}
2871-
// PyModule_GetFilenameObject raised "module filename missing"
2872-
_PyErr_Clear(tstate);
28732875
}
28742876
assert(origin == NULL || PyUnicode_Check(origin));
28752877
}

0 commit comments

Comments
 (0)