diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index e38d0942e463e9..0e6c7b6eec18c8 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -5109,6 +5109,26 @@ def func(): actual = self.get_suggestion(func) self.assertIn("forget to import '_io'", actual) + def test_name_error_do_not_suggest_builtin_name_in_delete(self): + def func(): + del next + + actual = self.get_suggestion(func) + self.assertNotIn("Did you mean: 'anext'", actual) + + def test_name_error_suggest_builtin_name_in_delete_if_not_delete_the_name_itself(self): + def func1(): + del nxt[1] + + actual = self.get_suggestion(func1) + self.assertIn("Did you mean: 'next'", actual) + + def func2(): + del nxt.__name__ + + actual = self.get_suggestion(func2) + self.assertIn("Did you mean: 'next'", actual) + class PurePythonSuggestionFormattingTests( diff --git a/Lib/traceback.py b/Lib/traceback.py index dcdab1f12e9a16..cbc7154fdb8fe6 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -14,6 +14,7 @@ import keyword import tokenize import io +import dis import importlib.util import pathlib @@ -1963,8 +1964,9 @@ def _compute_suggestion_error(exc_value, tb, wrong_name): d = ( list(frame.f_locals) + list(frame.f_globals) - + list(frame.f_builtins) ) + if not dis.opname[frame.f_code.co_code[frame.f_lasti]].startswith(('STORE_', 'DELETE_')): + d += list(frame.f_builtins) d = [x for x in d if isinstance(x, str)] if not_normalized and wrong_name in d: return wrong_name diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-11-11-14-21-33.gh-issue-138890.QwN0EU.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-11-11-14-21-33.gh-issue-138890.QwN0EU.rst new file mode 100644 index 00000000000000..2c8ff7b9ef869d --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-11-11-14-21-33.gh-issue-138890.QwN0EU.rst @@ -0,0 +1 @@ +Use a more simple way to forbidden the builtins name suggestion in deleting