https://github.com/python/cpython/commit/36d4f67b3cc97df8fb46f15e300719cc02cc496f
commit: 36d4f67b3cc97df8fb46f15e300719cc02cc496f
branch: 3.14
author: Miss Islington (bot) <[email protected]>
committer: vstinner <[email protected]>
date: 2025-12-10T16:07:59Z
summary:

[3.14] gh-142433: Move deref to below the error when checking for laststring 
(GH-142402) (#142524)

gh-142433: Move deref to below the error when checking for laststring 
(GH-142402)

Move deref of laststring to below the error checking so the deref
is applied after the object in strings is replaced.
(cherry picked from commit 785268fdceb0d0fe217aed1d6e43e0231c0e50c3)

Co-authored-by: AZero13 <[email protected]>

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2025-12-08-17-34-57.gh-issue-142402.iV0ON3.rst
M Objects/templateobject.c

diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2025-12-08-17-34-57.gh-issue-142402.iV0ON3.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2025-12-08-17-34-57.gh-issue-142402.iV0ON3.rst
new file mode 100644
index 00000000000000..bad31470a25552
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2025-12-08-17-34-57.gh-issue-142402.iV0ON3.rst
@@ -0,0 +1,3 @@
+Fix reference counting when adjacent literal parts are merged while 
constructing
+:class:`string.templatelib.Template`, preventing the displaced string object
+from leaking.
diff --git a/Objects/templateobject.c b/Objects/templateobject.c
index ac38e4de435d5d..a05208e4c8fc8e 100644
--- a/Objects/templateobject.c
+++ b/Objects/templateobject.c
@@ -148,13 +148,14 @@ template_new(PyTypeObject *type, PyObject *args, PyObject 
*kwds)
             if (last_was_str) {
                 PyObject *laststring = PyTuple_GET_ITEM(strings, stringsidx - 
1);
                 PyObject *concat = PyUnicode_Concat(laststring, item);
-                Py_DECREF(laststring);
                 if (!concat) {
                     Py_DECREF(strings);
                     Py_DECREF(interpolations);
                     return NULL;
                 }
+                /* Replace laststring with concat */
                 PyTuple_SET_ITEM(strings, stringsidx - 1, concat);
+                Py_DECREF(laststring);
             }
             else {
                 PyTuple_SET_ITEM(strings, stringsidx++, Py_NewRef(item));

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to