Skip to content

Commit 18a7f5d

Browse files
authored
gh-127598: Improve ModuleNotFoundError when -S is passed (GH-136821)
1 parent 4a151ca commit 18a7f5d

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/test/test_traceback.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4748,7 +4748,26 @@ class MyList(list):
47484748
with self.assertRaises(TypeError):
47494749
_suggestions._generate_suggestions(MyList(), "")
47504750

4751+
def test_no_site_package_flavour(self):
4752+
code = """import boo"""
4753+
_, _, stderr = assert_python_failure('-S', '-c', code)
47514754

4755+
self.assertIn(
4756+
(b"Site initialization is disabled, did you forget to "
4757+
b"add the site-packages directory to sys.path?"), stderr
4758+
)
4759+
4760+
code = """
4761+
import sys
4762+
sys.stdlib_module_names = sys.stdlib_module_names + ("boo",)
4763+
import boo
4764+
"""
4765+
_, _, stderr = assert_python_failure('-S', '-c', code)
4766+
4767+
self.assertNotIn(
4768+
(b"Site initialization is disabled, did you forget to "
4769+
b"add the site-packages directory to sys.path?"), stderr
4770+
)
47524771

47534772

47544773
class TestColorizedTraceback(unittest.TestCase):

Lib/traceback.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,11 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11061106
suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
11071107
if suggestion:
11081108
self._str += f". Did you mean: '{suggestion}'?"
1109+
elif exc_type and issubclass(exc_type, ModuleNotFoundError) and \
1110+
sys.flags.no_site and \
1111+
getattr(exc_value, "name", None) not in sys.stdlib_module_names:
1112+
self._str += (". Site initialization is disabled, did you forget to "
1113+
+ "add the site-packages directory to sys.path?")
11091114
elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
11101115
getattr(exc_value, "name", None) is not None:
11111116
wrong_name = getattr(exc_value, "name", None)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`ModuleNotFoundError` by adding flavour text to the exception when the
2+
:option:`-S` option is passed. Patch by Andrea Mattei.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy