Skip to content

Commit a41de32

Browse files
authored
gh-98878: Use builtins from the bound frame when offering a suggestion (#98880)
1 parent 39448ad commit a41de32

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

Lib/test/test_traceback.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import types
88
import inspect
99
import importlib
10+
import builtins
1011
import unittest
1112
import re
1213
import tempfile
@@ -3209,6 +3210,14 @@ def func():
32093210
actual = self.get_suggestion(func)
32103211
self.assertIn("'ZeroDivisionError'?", actual)
32113212

3213+
def test_name_error_suggestions_from_builtins_when_builtins_is_module(self):
3214+
def func():
3215+
custom_globals = globals().copy()
3216+
custom_globals["__builtins__"] = builtins
3217+
print(eval("ZeroDivisionErrrrr", custom_globals))
3218+
actual = self.get_suggestion(func)
3219+
self.assertIn("'ZeroDivisionError'?", actual)
3220+
32123221
def test_name_error_suggestions_do_not_trigger_for_long_names(self):
32133222
def func():
32143223
somethingverywronghehehehehehe = None

Lib/traceback.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1035,7 +1035,7 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
10351035
d = (
10361036
list(frame.f_locals)
10371037
+ list(frame.f_globals)
1038-
+ list(frame.f_globals['__builtins__'])
1038+
+ list(frame.f_builtins)
10391039
)
10401040
if len(d) > _MAX_CANDIDATE_ITEMS:
10411041
return None
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Use the frame bound builtins when offering a name suggestion in
2+
:mod:`traceback` to prevent crashing when ``__builtins__`` is not a dict.

0 commit comments

Comments
 (0)