Skip to content

Commit

Permalink
pythongh-98878: Use builtins from the bound frame when offering a sug…
Browse files Browse the repository at this point in the history
…gestion
  • Loading branch information
isidentical committed Oct 30, 2022
1 parent 018b248 commit fe5d65c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
9 changes: 9 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import types
import inspect
import importlib
import builtins
import unittest
import re
import tempfile
Expand Down Expand Up @@ -3209,6 +3210,14 @@ def func():
actual = self.get_suggestion(func)
self.assertIn("'ZeroDivisionError'?", actual)

def test_name_error_suggestions_from_builtins_when_builtins_is_module(self):
def func():
custom_globals = globals().copy()
custom_globals["__builtins__"] = builtins

This comment has been minimized.

Copy link
@iritkatriel

iritkatriel Oct 30, 2022

You could just do:

custom_globals["__builtins__"] = {'ZeroDivisionErrrrror': 42}

The you get

NameError: name 'ZeroDivisionErrrrr' is not defined. Did you mean: 'ZeroDivisionErrrrror'?

print(eval("ZeroDivisionErrrrr", custom_globals))
actual = self.get_suggestion(func)
self.assertIn("'ZeroDivisionError'?", actual)

def test_name_error_suggestions_do_not_trigger_for_long_names(self):
def func():
somethingverywronghehehehehehe = None
Expand Down
2 changes: 1 addition & 1 deletion Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,7 +1035,7 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
d = (
list(frame.f_locals)
+ list(frame.f_globals)
+ list(frame.f_globals['__builtins__'])
+ list(frame.f_builtins)
)
if len(d) > _MAX_CANDIDATE_ITEMS:
return None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Use the frame bound builtins when offering a name suggestion in
:mod:`traceback` to prevent crashing when ``__builtins__`` is not a dict.

0 comments on commit fe5d65c

Please sign in to comment.