Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import tokenize
import io
import importlib.util
from importlib.machinery import ModuleSpec
Comment thread
Locked-chess-official marked this conversation as resolved.
Outdated
import pathlib
import _colorize

Expand Down Expand Up @@ -1125,16 +1126,14 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
self._str += f". Did you mean: '{suggestion}' ({suggestion!a})?"
elif exc_type and issubclass(exc_type, ModuleNotFoundError):
module_name = getattr(exc_value, "name", None)
analyse_sys_no_site = True
if module_name in sys.stdlib_module_names:
message = _MISSING_STDLIB_MODULE_MESSAGES.get(
module_name,
f"Standard library module {module_name!r} was not found"
)
self._str = message
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?")
analyse_sys_no_site = False
elif abi_tag := _find_incompatible_extension_module(module_name):
self._str += (
". Although a module with this name was found for a "
Expand All @@ -1144,6 +1143,12 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
suggestion = _compute_suggestion_error(exc_value, exc_traceback, module_name)
if suggestion:
self._str += f". Did you mean: '{suggestion}'?"
if analyse_sys_no_site and sys.flags.no_site:
if not self._str.endswith((".", "?")):
self._str += "."
self._str += (" Site initialization is disabled, did you forget to "
"add the site-packages directory to sys.path "
"or to enable your virtual environment?")
Comment on lines +1145 to +1150
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the analyse_sys_no_site variable makes the code a bit difficult to read. I'd prefer just putting the module_name in sys.stdlib_module_names check here again..

elif exc_type and issubclass(exc_type, AttributeError) and \
getattr(exc_value, "name", None) is not None:
wrong_name = getattr(exc_value, "name", None)
Expand Down Expand Up @@ -1758,7 +1763,10 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
d = []
for finder in sys.meta_path:
if discover := getattr(finder, 'discover', None):
d += [spec.name for spec in discover(parent)]
try:
d += [spec.name for spec in discover(parent) if isinstance(spec, ModuleSpec)]
except Exception:
continue
Comment thread
Locked-chess-official marked this conversation as resolved.
Outdated
except Exception:
return None
elif isinstance(exc_value, ImportError):
Expand Down
Loading