https://github.com/python/cpython/commit/18a7f5dad832488e8965fe29159a62abc18368e2
commit: 18a7f5dad832488e8965fe29159a62abc18368e2
branch: main
author: MonadChains <[email protected]>
committer: encukou <[email protected]>
date: 2025-07-20T15:33:58+02:00
summary:
gh-127598: Improve ModuleNotFoundError when -S is passed (GH-136821)
files:
A
Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst
M Lib/test/test_traceback.py
M Lib/traceback.py
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index 74b979d009664d..11b7f419bddbe4 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -4748,7 +4748,26 @@ class MyList(list):
with self.assertRaises(TypeError):
_suggestions._generate_suggestions(MyList(), "")
+ def test_no_site_package_flavour(self):
+ code = """import boo"""
+ _, _, stderr = assert_python_failure('-S', '-c', code)
+ self.assertIn(
+ (b"Site initialization is disabled, did you forget to "
+ b"add the site-packages directory to sys.path?"), stderr
+ )
+
+ code = """
+ import sys
+ sys.stdlib_module_names = sys.stdlib_module_names + ("boo",)
+ import boo
+ """
+ _, _, stderr = assert_python_failure('-S', '-c', code)
+
+ self.assertNotIn(
+ (b"Site initialization is disabled, did you forget to "
+ b"add the site-packages directory to sys.path?"), stderr
+ )
class TestColorizedTraceback(unittest.TestCase):
diff --git a/Lib/traceback.py b/Lib/traceback.py
index 31aa8695735f2b..f0dbb6352f7760 100644
--- a/Lib/traceback.py
+++ b/Lib/traceback.py
@@ -1106,6 +1106,11 @@ def __init__(self, exc_type, exc_value, exc_traceback,
*, limit=None,
suggestion = _compute_suggestion_error(exc_value, exc_traceback,
wrong_name)
if suggestion:
self._str += f". Did you mean: '{suggestion}'?"
+ elif exc_type and issubclass(exc_type, ModuleNotFoundError) and \
+ sys.flags.no_site and \
+ getattr(exc_value, "name", None) not in
sys.stdlib_module_names:
+ self._str += (". Site initialization is disabled, did you forget
to "
+ + "add the site-packages directory to sys.path?")
elif exc_type and issubclass(exc_type, (NameError, AttributeError))
and \
getattr(exc_value, "name", None) is not None:
wrong_name = getattr(exc_value, "name", None)
diff --git
a/Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst
b/Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst
new file mode 100644
index 00000000000000..aff047bbef0f07
--- /dev/null
+++
b/Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst
@@ -0,0 +1,2 @@
+Improve :exc:`ModuleNotFoundError` by adding flavour text to the exception
when the
+:option:`-S` option is passed. Patch by Andrea Mattei.
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]