From 9b4154c1fe37dd0785a04b7cc00919bef3f4e9ab Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 13 Aug 2026 20:35:51 +0200 Subject: [PATCH 1/2] gh-155742: Use PyBytesWriter in codecs Replace soft deprecated PyBytes_FromStringAndSize() with PyBytesWriter. --- Python/codecs.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/codecs.c b/Python/codecs.c index 6d1ae651fa00058..ea3a34f619c43ad 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -1426,19 +1426,19 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc) return NULL; } - PyObject *res = PyBytes_FromStringAndSize(NULL, slen); - if (res == NULL) { + PyBytesWriter *writer = PyBytesWriter_Create(slen); + if (writer == NULL) { Py_DECREF(obj); return NULL; } - char *outp = PyBytes_AsString(res); + char *outp = PyBytesWriter_GetData(writer); for (Py_ssize_t i = start; i < end; i++) { Py_UCS4 ch = PyUnicode_READ_CHAR(obj, i); if (ch < 0xdc80 || ch > 0xdcff) { /* Not a UTF-8b surrogate, fail with original exception. */ Py_DECREF(obj); - Py_DECREF(res); + PyBytesWriter_Discard(writer); PyErr_SetObject(PyExceptionInstance_Class(exc), exc); return NULL; } @@ -1446,6 +1446,7 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc) } Py_DECREF(obj); + PyObject *res = PyBytesWriter_Finish(writer); // can be NULL return Py_BuildValue("(Nn)", res, end); } From 304af9afc0856ad8a738819da36033a4f818d271 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 13 Aug 2026 21:26:54 +0200 Subject: [PATCH 2/2] Update the comment about NULL result --- Python/codecs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/codecs.c b/Python/codecs.c index ea3a34f619c43ad..84a0589c8e8317e 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -1446,7 +1446,8 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc) } Py_DECREF(obj); - PyObject *res = PyBytesWriter_Finish(writer); // can be NULL + PyObject *res = PyBytesWriter_Finish(writer); + // Py_BuildValue() propagates the exception if res is NULL return Py_BuildValue("(Nn)", res, end); }