Skip to content

gh-128030: Avoid error from PyModule_GetFilenameObject for non-module #128047

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,29 @@ def test_frozen_module_from_import_error(self):
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 = [
(
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion Python/ceval.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading