diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index ce9c060641d6c5..9cc025d85e168a 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -1636,6 +1636,16 @@ async def name_4(): pass [[]] + def test_globals_dict_subclass(self): + # gh-132386 + class WeirdDict(dict): + pass + + ns = {} + exec('def foo(): return a', WeirdDict(), ns) + + self.assertRaises(NameError, ns['foo']) + class TestBooleanExpression(unittest.TestCase): class Value: def __init__(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst new file mode 100644 index 00000000000000..65ba7fc182b674 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-11-18-46-37.gh-issue-132386.pMBFTe.rst @@ -0,0 +1,2 @@ +Fix crash when passing a dict subclass as the ``globals`` parameter to +:func:`exec`. diff --git a/Python/ceval.c b/Python/ceval.c index 8ab0c6318c1c91..e4a63ad9287783 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -3312,6 +3312,8 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name _PyEval_FormatExcCheckArg( PyThreadState_GET(), PyExc_NameError, NAME_ERROR_MSG, name); + *writeto = PyStackRef_NULL; + return; } } *writeto = PyStackRef_FromPyObjectSteal(res);