diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index d5b00a3bb628cb..9c13316f3fea6e 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -5325,6 +5325,20 @@ def test_windows_only_module_error(self): else: self.fail("ModuleNotFoundError was not raised") + def test_module_not_found_without_search_paths(self): + importlib.import_module('importlib.resources.readers') + error = ModuleNotFoundError("No module named 'missing_module'", + name='missing_module') + with os_helper.temp_dir() as tmp: + for paths in ([], [os.path.join(tmp, 'missing')]): + with self.subTest(paths=paths): + with support.swap_attr(sys, 'path', paths): + self.assertEqual( + traceback.format_exception_only(error), + ["ModuleNotFoundError: No module named " + "'missing_module'\n"], + ) + @unittest.skipIf(not importlib.machinery.EXTENSION_SUFFIXES, 'Platform does not support extension modules') def test_find_incompatible_extension_modules(self): """_find_incompatible_extension_modules assumes the last extension in diff --git a/Lib/traceback.py b/Lib/traceback.py index dcdab1f12e9a16..b27af6990daf38 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -2106,9 +2106,10 @@ def _find_incompatible_extension_module(module_name): if parent: traversable = importlib.resources.files(parent) else: - traversable = importlib.resources.readers.MultiplexedPath( - *map(pathlib.Path, filter(os.path.isdir, sys.path)) - ) + paths = list(map(pathlib.Path, filter(os.path.isdir, sys.path))) + if not paths: + return + traversable = importlib.resources.readers.MultiplexedPath(*paths) for entry in traversable.iterdir(): if entry.name.startswith(child + '.') and entry.name.endswith(untagged_suffix): diff --git a/Misc/NEWS.d/next/Library/2026-10-20-02-01-00.gh-issue-159693.6Rky2a.rst b/Misc/NEWS.d/next/Library/2026-10-20-02-01-00.gh-issue-159693.6Rky2a.rst new file mode 100644 index 00000000000000..a00a941d7b8ee7 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-20-02-01-00.gh-issue-159693.6Rky2a.rst @@ -0,0 +1,2 @@ +Fix formatting of :exc:`ModuleNotFoundError` when :data:`sys.path` contains +no existing directories, including when displaying errors in the REPL.