[3.13] gh-128030: Avoid error from PyModule_GetFilenameObject for non-module (GH-128047) (#128114)

gh-128030: Avoid error from PyModule_GetFilenameObject for non-module (GH-128047)

I missed the extra `PyModule_Check` in GH-127660 because I was looking at
3.12 as the base implementation for import from. This meant that I
missed the `PyModuleCheck` introduced in GH-112661.
(cherry picked from commit 45e6dd63b8)

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2024-12-20 09:46:54 +01:00 committed by GitHub
parent 3a8bdaf698
commit f320f747da
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 25 additions and 1 deletions

View file

@ -870,6 +870,29 @@ from os import this_will_never_exist
stdout, stderr = popen.communicate() stdout, stderr = popen.communicate()
self.assertIn(expected_error, stdout) 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): def test_script_shadowing_stdlib(self):
script_errors = [ script_errors = [
( (

View file

@ -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.

View file

@ -2781,7 +2781,7 @@ import_from(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 // Fall back to __file__ for diagnostics if we don't have
// an origin that is a location // an origin that is a location
origin = PyModule_GetFilenameObject(v); origin = PyModule_GetFilenameObject(v);