https://github.com/python/cpython/commit/3ca92d959816d27c39041c0caa9c6fd53ad925fe
commit: 3ca92d959816d27c39041c0caa9c6fd53ad925fe
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: vstinner <[email protected]>
date: 2026-10-13T00:05:44Z
summary:

[3.15] gh-157242: Do not close io.BytesIO on MemoryError (GH-157344) (#159275)

gh-157242: Do not close io.BytesIO on MemoryError (GH-157344)

Replace _PyBytes_Resize() with _PyBytes_ResizeKeepOnError().

Fix truncate(): on error, restore string_size to its previous value.
(cherry picked from commit 23eda007f8d543495ba4935df75d243d76f9ef7f)

Co-authored-by: Victor Stinner <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-09-12-03-14-57.gh-issue-157242.ycbtjC.rst
M Lib/test/test_io/test_memoryio.py
M Modules/_io/bytesio.c

diff --git a/Lib/test/test_io/test_memoryio.py 
b/Lib/test/test_io/test_memoryio.py
index 8780796ce831ee..6e436b5a547836 100644
--- a/Lib/test/test_io/test_memoryio.py
+++ b/Lib/test/test_io/test_memoryio.py
@@ -5,6 +5,7 @@
 
 import unittest
 from test import support
+from test.support import import_helper
 
 import gc
 import io
@@ -651,6 +652,35 @@ def __buffer__(self, flags):
         self.assertEqual(memio.getvalue(), b"01AAA56789")
         self.assertEqual(memio.tell(), 5)
 
+    def test_memory_error(self):
+        # gh-157242: io.BytesIO() must not close the file on MemoryError
+        _testcapi = import_helper.import_module('_testcapi')
+
+        # write()
+        stream = self.ioclass()
+        stream.write(self.buftype('abc'))
+        with self.assertRaises(MemoryError):
+            try:
+                data = self.buftype('def')
+                _testcapi.set_nomemory(0)
+                stream.write(data)
+            finally:
+                _testcapi.remove_mem_hooks()
+        stream.write(self.buftype('123'))
+        self.assertEqual(stream.getvalue(), self.buftype('abc123'))
+
+        # truncate()
+        data = self.buftype('x' * 100)
+        stream = self.ioclass()
+        stream.write(data)
+        with self.assertRaises(MemoryError):
+            try:
+                _testcapi.set_nomemory(0)
+                stream.truncate(5)
+            finally:
+                _testcapi.remove_mem_hooks()
+        self.assertEqual(stream.getvalue(), data)
+
 
 class TextIOTestMixin:
 
diff --git 
a/Misc/NEWS.d/next/Library/2026-09-12-03-14-57.gh-issue-157242.ycbtjC.rst 
b/Misc/NEWS.d/next/Library/2026-09-12-03-14-57.gh-issue-157242.ycbtjC.rst
new file mode 100644
index 00000000000000..54ada2892f76fa
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-09-12-03-14-57.gh-issue-157242.ycbtjC.rst
@@ -0,0 +1,2 @@
+:class:`io.BytesIO` is no longer closed on ``write()`` and ``truncate()``
+failure (:exc:`MemoryError`). Patch by Victor Stinner.
diff --git a/Modules/_io/bytesio.c b/Modules/_io/bytesio.c
index da2b480ed1cf51..9ea197d29f3096 100644
--- a/Modules/_io/bytesio.c
+++ b/Modules/_io/bytesio.c
@@ -1,4 +1,5 @@
 #include "Python.h"
+#include "pycore_bytesobject.h"       // _PyBytes_ResizeKeepOnError()
 #include "pycore_critical_section.h"  // Py_BEGIN_CRITICAL_SECTION()
 #include "pycore_object.h"
 #include "pycore_pyatomic_ft_wrappers.h"
@@ -107,7 +108,7 @@ resize_unshared_buffer_lock_held(bytesio *self, Py_ssize_t 
size)
        Callers must detach first. */
     assert(!self->buf_shared);
 #endif
-    int ret = _PyBytes_Resize(&self->buf, size);
+    int ret = _PyBytes_ResizeKeepOnError(&self->buf, size);
     if (ret == 0) {
         clear_shared_buf(self);
     }
@@ -712,9 +713,12 @@ _io_BytesIO_truncate_impl(bytesio *self, PyObject *size)
     }
 
     if (new_size < self->string_size) {
+        Py_ssize_t old_string_size = self->string_size;
         self->string_size = new_size;
-        if (resize_buffer_lock_held(self, new_size) < 0)
+        if (resize_buffer_lock_held(self, new_size) < 0) {
+            self->string_size = old_string_size;
             return NULL;
+        }
     }
 
     return PyLong_FromSsize_t(new_size);

_______________________________________________
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