Skip to content

Commit 3ef83d6

Browse files
committed
gh-134872: Add traceback suggestions for ModuleNotFoundError
Signed-off-by: Filipe Laíns <lains@riseup.net>
1 parent 8099249 commit 3ef83d6

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Lib/traceback.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import keyword
1111
import tokenize
1212
import io
13+
import importlib.util
1314
import _colorize
1415

1516
from contextlib import suppress
@@ -1124,6 +1125,10 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11241125
self._str += (". Site initialization is disabled, did you forget to "
11251126
+ "add the site-packages directory to sys.path "
11261127
+ "or to enable your virtual environment?")
1128+
else:
1129+
suggestion = _compute_suggestion_error(exc_value, exc_traceback, module_name)
1130+
if suggestion:
1131+
self._str += f". Did you mean: '{suggestion}'?"
11271132
elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
11281133
getattr(exc_value, "name", None) is not None:
11291134
wrong_name = getattr(exc_value, "name", None)
@@ -1672,6 +1677,21 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
16721677
d = [x for x in d if x[:1] != '_']
16731678
except Exception:
16741679
return None
1680+
elif isinstance(exc_value, ModuleNotFoundError):
1681+
try:
1682+
if parent_name := wrong_name.rpartition('.')[0]:
1683+
parent = importlib.util.find_spec(parent_name)
1684+
else:
1685+
parent = None
1686+
d = []
1687+
for finder in sys.meta_path:
1688+
try:
1689+
discover = getattr(finder, 'discover')
1690+
except AttributeError:
1691+
continue
1692+
d += [spec.name for spec in discover(parent)]
1693+
except Exception:
1694+
return None
16751695
elif isinstance(exc_value, ImportError):
16761696
try:
16771697
mod = __import__(exc_value.name)

0 commit comments

Comments
 (0)