From 1ba5e65b76eb0d745e63691bda7206e66f72a961 Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Sat, 17 May 2025 21:48:54 +0200 Subject: [PATCH] [3.14] gh-134119: Fix crash from calling next() on exhausted template iterator (GH-134120) (#134153) MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit gh-134119: Fix crash from calling next() on exhausted template iterator (GH-134120) (cherry picked from commit fc7f4c36664314393bd4c30355e21bd7aeac524d) Co-authored-by: Jelle Zijlstra Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- Lib/test/test_string/test_templatelib.py | 7 +++++++ .../2025-05-16-20-59-12.gh-issue-134119.w8expI.rst | 2 ++ Objects/templateobject.c | 3 +++ 3 files changed, 12 insertions(+) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst diff --git a/Lib/test/test_string/test_templatelib.py b/Lib/test/test_string/test_templatelib.py index 5b9490c2be6d..85fcff486d66 100644 --- a/Lib/test/test_string/test_templatelib.py +++ b/Lib/test/test_string/test_templatelib.py @@ -148,6 +148,13 @@ class TemplateIterTests(unittest.TestCase): self.assertEqual(res[1].format_spec, '') self.assertEqual(res[2], ' yz') + def test_exhausted(self): + # See https://github.com/python/cpython/issues/134119. + template_iter = iter(t"{1}") + self.assertIsInstance(next(template_iter), Interpolation) + self.assertRaises(StopIteration, next, template_iter) + self.assertRaises(StopIteration, next, template_iter) + if __name__ == '__main__': unittest.main() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst new file mode 100644 index 000000000000..754e81662856 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst @@ -0,0 +1,2 @@ +Fix crash when calling :func:`next` on an exhausted template string iterator. +Patch by Jelle Zijlstra. diff --git a/Objects/templateobject.c b/Objects/templateobject.c index 06cb19e0b6d0..4293a311c440 100644 --- a/Objects/templateobject.c +++ b/Objects/templateobject.c @@ -23,6 +23,9 @@ templateiter_next(PyObject *op) if (self->from_strings) { item = PyIter_Next(self->stringsiter); self->from_strings = 0; + if (item == NULL) { + return NULL; + } if (PyUnicode_GET_LENGTH(item) == 0) { Py_SETREF(item, PyIter_Next(self->interpolationsiter)); self->from_strings = 1; -- 2.47.3