diff options
author | Pablo Galindo Salgado <Pablogsal@gmail.com> | 2022-10-25 22:56:59 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-10-25 22:56:59 (GMT) |
commit | 7cfbb49fcd4c85f9bab3797302eadf93df490344 (patch) | |
tree | a20c316c8296dbe3e327e7fcf19925e8090ee267 /Lib/traceback.py | |
parent | 1f737edb67e702095feb97118a911afb569f5705 (diff) | |
download | cpython-7cfbb49fcd4c85f9bab3797302eadf93df490344.zip cpython-7cfbb49fcd4c85f9bab3797302eadf93df490344.tar.gz cpython-7cfbb49fcd4c85f9bab3797302eadf93df490344.tar.bz2 |
gh-91058: Add error suggestions to 'import from' import errors (#98305)
Diffstat (limited to 'Lib/traceback.py')
-rw-r--r-- | Lib/traceback.py | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/Lib/traceback.py b/Lib/traceback.py index bb7856a..6270100 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -707,9 +707,16 @@ class TracebackException: self.offset = exc_value.offset self.end_offset = exc_value.end_offset self.msg = exc_value.msg + elif exc_type and issubclass(exc_type, ImportError) and \ + getattr(exc_value, "name_from", None) is not None: + wrong_name = getattr(exc_value, "name_from", None) + suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) + if suggestion: + self._str += f". Did you mean: '{suggestion}'?" elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \ getattr(exc_value, "name", None) is not None: - suggestion = _compute_suggestion_error(exc_value, exc_traceback) + wrong_name = getattr(exc_value, "name", None) + suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) if suggestion: self._str += f". Did you mean: '{suggestion}'?" if issubclass(exc_type, NameError): @@ -1005,8 +1012,7 @@ def _substitution_cost(ch_a, ch_b): return _MOVE_COST -def _compute_suggestion_error(exc_value, tb): - wrong_name = getattr(exc_value, "name", None) +def _compute_suggestion_error(exc_value, tb, wrong_name): if wrong_name is None or not isinstance(wrong_name, str): return None if isinstance(exc_value, AttributeError): @@ -1015,6 +1021,12 @@ def _compute_suggestion_error(exc_value, tb): d = dir(obj) except Exception: return None + elif isinstance(exc_value, ImportError): + try: + mod = __import__(exc_value.name) + d = dir(mod) + except Exception: + return None else: assert isinstance(exc_value, NameError) # find most recent frame |