]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-134119: Fix crash from calling next() on exhausted template iterator (#134120)
authorJelle Zijlstra <jelle.zijlstra@gmail.com>
Sat, 17 May 2025 19:23:19 +0000 (12:23 -0700)
committerGitHub <noreply@github.com>
Sat, 17 May 2025 19:23:19 +0000 (12:23 -0700)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Lib/test/test_string/test_templatelib.py
Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst [new file with mode: 0644]
Objects/templateobject.c

index 5b9490c2be6de076df6a3a3a1adf0ee5f7331f49..85fcff486d661630a3e66727680c33d6bdea45f0 100644 (file)
@@ -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 (file)
index 0000000..754e816
--- /dev/null
@@ -0,0 +1,2 @@
+Fix crash when calling :func:`next` on an exhausted template string iterator.
+Patch by Jelle Zijlstra.
index 06cb19e0b6d0562a32663db33ca0530fed41d799..4293a311c440f7a66a8bd016e2cacd27446d1f79 100644 (file)
@@ -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;