gh-139707: Better ModuleNotFoundError message for missing stdlib modules (GH-140219)

This commit is contained in:
Stan Ulbrych 2025-10-21 08:12:04 +01:00 committed by GitHub
parent b2f9fb9db2
commit 47d2f68df2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 24 additions and 7 deletions

View file

@ -5034,7 +5034,8 @@ def test_no_site_package_flavour(self):
self.assertIn( self.assertIn(
(b"Site initialization is disabled, did you forget to " (b"Site initialization is disabled, did you forget to "
b"add the site-packages directory to sys.path?"), stderr b"add the site-packages directory to sys.path "
b"or to enable your virtual environment?"), stderr
) )
code = """ code = """
@ -5046,9 +5047,20 @@ def test_no_site_package_flavour(self):
self.assertNotIn( self.assertNotIn(
(b"Site initialization is disabled, did you forget to " (b"Site initialization is disabled, did you forget to "
b"add the site-packages directory to sys.path?"), stderr b"add the site-packages directory to sys.path "
b"or to enable your virtual environment?"), stderr
) )
def test_missing_stdlib_package(self):
code = """
import sys
sys.stdlib_module_names |= {'spam'}
import spam
"""
_, _, stderr = assert_python_failure('-S', '-c', code)
self.assertIn(b"Standard library module 'spam' was not found", stderr)
class TestColorizedTraceback(unittest.TestCase): class TestColorizedTraceback(unittest.TestCase):
maxDiff = None maxDiff = None

View file

@ -1107,11 +1107,14 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
if suggestion: if suggestion:
self._str += f". Did you mean: '{suggestion}'?" self._str += f". Did you mean: '{suggestion}'?"
elif exc_type and issubclass(exc_type, ModuleNotFoundError) and \ elif exc_type and issubclass(exc_type, ModuleNotFoundError):
sys.flags.no_site and \ module_name = getattr(exc_value, "name", None)
getattr(exc_value, "name", None) not in sys.stdlib_module_names: if module_name in sys.stdlib_module_names:
self._str += (". Site initialization is disabled, did you forget to " self._str = f"Standard library module '{module_name}' was not found"
+ "add the site-packages directory to sys.path?") elif sys.flags.no_site:
self._str += (". Site initialization is disabled, did you forget to "
+ "add the site-packages directory to sys.path "
+ "or to enable your virtual environment?")
elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \ elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
getattr(exc_value, "name", None) is not None: getattr(exc_value, "name", None) is not None:
wrong_name = getattr(exc_value, "name", None) wrong_name = getattr(exc_value, "name", None)

View file

@ -0,0 +1,2 @@
Improve :exc:`ModuleNotFoundError` error message when a :term:`standard library`
module is missing.