https://github.com/python/cpython/commit/fc7f4c36664314393bd4c30355e21bd7aeac524d
commit: fc7f4c36664314393bd4c30355e21bd7aeac524d
branch: main
author: Jelle Zijlstra <jelle.zijls...@gmail.com>
committer: JelleZijlstra <jelle.zijls...@gmail.com>
date: 2025-05-17T12:23:19-07:00
summary:

gh-134119: Fix crash from calling next() on exhausted template iterator 
(#134120)

Co-authored-by: Bénédikt Tran <10796600+picn...@users.noreply.github.com>

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2025-05-16-20-59-12.gh-issue-134119.w8expI.rst
M Lib/test/test_string/test_templatelib.py
M Objects/templateobject.c

diff --git a/Lib/test/test_string/test_templatelib.py 
b/Lib/test/test_string/test_templatelib.py
index 5b9490c2be6de0..85fcff486d6616 100644
--- a/Lib/test/test_string/test_templatelib.py
+++ b/Lib/test/test_string/test_templatelib.py
@@ -148,6 +148,13 @@ def test_iter(self):
         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 00000000000000..754e816628563e
--- /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 06cb19e0b6d056..4293a311c440f7 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;

_______________________________________________
Python-checkins mailing list -- python-checkins@python.org
To unsubscribe send an email to python-checkins-le...@python.org
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: arch...@mail-archive.com

Reply via email to