diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py index ce2fac1f641900..f3d9a5a19772f3 100644 --- a/Lib/test/test_io.py +++ b/Lib/test/test_io.py @@ -2296,6 +2296,15 @@ def test_write(self): pair.flush() self.assertEqual(w._write_stack, [b"abc", b"def"]) + def test_destructor_flushes_shared_stream(self): + raw = self.MockRawIO() + pair = self.tp(raw, raw) + pair.write(b"abc") + self.assertEqual(raw._write_stack, []) + del pair + support.gc_collect() + self.assertEqual(raw._write_stack, [b"abc"]) + def test_peek(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) diff --git a/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst new file mode 100644 index 00000000000000..702b38215ed6ef --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-19-22-01-29.gh-issue-162246.y3L8nP.rst @@ -0,0 +1,2 @@ +Fix :class:`io.BufferedRWPair` losing buffered writes on deallocation when the +reader and writer share a raw stream. diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c index 50769e419303fe..426c6176380b14 100644 --- a/Modules/_io/bufferedio.c +++ b/Modules/_io/bufferedio.c @@ -2302,8 +2302,9 @@ static int bufferedrwpair_clear(PyObject *op) { rwpair *self = rwpair_CAST(op); - Py_CLEAR(self->reader); + /* Let the writer flush before the reader closes a shared raw stream. */ Py_CLEAR(self->writer); + Py_CLEAR(self->reader); Py_CLEAR(self->dict); return 0; }