From f320f747da2ad7b1eb039b2d7b475e0ac057fa49 Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Fri, 20 Dec 2024 09:46:54 +0100 Subject: [PATCH] [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 45e6dd63b88a782f2ec96ab1da54eb5a074d8f4c) Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com> --- Lib/test/test_import/__init__.py | 23 +++++++++++++++++++ ...-12-17-22-28-15.gh-issue-128030.H1ptOD.rst | 1 + Python/ceval.c | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2024-12-17-22-28-15.gh-issue-128030.H1ptOD.rst diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py index 58c6aaf0986bcf..364ff08f03533b 100644 --- a/Lib/test/test_import/__init__.py +++ b/Lib/test/test_import/__init__.py @@ -870,6 +870,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 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 index 00000000000000..93d78632355b76 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-17-22-28-15.gh-issue-128030.H1ptOD.rst @@ -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. diff --git a/Python/ceval.c b/Python/ceval.c index 4796ed301826fd..64424ed939fc5b 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -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 // an origin that is a location origin = PyModule_GetFilenameObject(v);