Skip to content

Commit f282f7a

Browse files
authored
GH-134872: add ModuleNotFoundError suggestions (#142512)
* gh-134872: Add traceback suggestions for ModuleNotFoundError Signed-off-by: Filipe Laíns <lains@riseup.net> * Add news Signed-off-by: Filipe Laíns <lains@riseup.net> --------- Signed-off-by: Filipe Laíns <lains@riseup.net>
1 parent 157f271 commit f282f7a

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

Lib/traceback.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import keyword
1212
import tokenize
1313
import io
14+
import importlib.util
1415
import _colorize
1516

1617
from contextlib import suppress
@@ -1128,6 +1129,10 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11281129
self._str += (". Site initialization is disabled, did you forget to "
11291130
+ "add the site-packages directory to sys.path "
11301131
+ "or to enable your virtual environment?")
1132+
else:
1133+
suggestion = _compute_suggestion_error(exc_value, exc_traceback, module_name)
1134+
if suggestion:
1135+
self._str += f". Did you mean: '{suggestion}'?"
11311136
elif exc_type and issubclass(exc_type, AttributeError) and \
11321137
getattr(exc_value, "name", None) is not None:
11331138
wrong_name = getattr(exc_value, "name", None)
@@ -1717,6 +1722,18 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
17171722
d = [x for x in d if x[:1] != '_']
17181723
except Exception:
17191724
return None
1725+
elif isinstance(exc_value, ModuleNotFoundError):
1726+
try:
1727+
if parent_name := wrong_name.rpartition('.')[0]:
1728+
parent = importlib.util.find_spec(parent_name)
1729+
else:
1730+
parent = None
1731+
d = []
1732+
for finder in sys.meta_path:
1733+
if discover := getattr(finder, 'discover', None):
1734+
d += [spec.name for spec in discover(parent)]
1735+
except Exception:
1736+
return None
17201737
elif isinstance(exc_value, ImportError):
17211738
try:
17221739
mod = __import__(exc_value.name)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add valid import name suggestions on :exc:`ModuleNotFoundError`.

0 commit comments

Comments
 (0)