diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 913d007a126d72..87914ade5b518f 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1013,8 +1013,24 @@ def four_freevars(): three_freevars.__code__, three_freevars.__globals__, closure=my_closure) + my_closure = tuple(my_closure) + + # should fail: anything passed to closure= isn't allowed + # when the source is a string + self.assertRaises(TypeError, + exec, + "pass", + closure=int) + + # should fail: correct closure= argument isn't allowed + # when the source is a string + self.assertRaises(TypeError, + exec, + "pass", + closure=my_closure) # should fail: closure tuple with one non-cell-var + my_closure = list(my_closure) my_closure[0] = int my_closure = tuple(my_closure) self.assertRaises(TypeError, diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-02-13-05-09-31.gh-issue-130070.C8c9gK.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-02-13-05-09-31.gh-issue-130070.C8c9gK.rst new file mode 100644 index 00000000000000..f9e135f1902b8a --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-02-13-05-09-31.gh-issue-130070.C8c9gK.rst @@ -0,0 +1 @@ +Fixed an assertion error for :func:`exec` passed a string ``source`` and a non-``None`` ``closure``. Patch by Bartosz Sławecki. diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 46a6fd9a8ef017..0c7b45c0b9b48d 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1175,6 +1175,7 @@ builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals, if (closure != NULL) { PyErr_SetString(PyExc_TypeError, "closure can only be used when source is a code object"); + goto error; } PyObject *source_copy; const char *str;