https://github.com/python/cpython/commit/a182cc80778bc2a45a7855fbce89fcbf65993025
commit: a182cc80778bc2a45a7855fbce89fcbf65993025
branch: 3.14
author: Cody Maloney <[email protected]>
committer: cmaloney <[email protected]>
date: 2026-11-22T13:33:27-08:00
summary:

[3.14] gh-138720: Make Buffered closed check match flush (GH-138724) (#162459)

In `_io__Buffered_flush_impl` the macro `CHECK_CLOSED` is used to check
the `buffered*` is in a good state to be flushed. That differs slightly
from `buffered_closed`.

In some cases, that difference would result in `close()` thinking the
file needed to be flushed and closed while `flush()` thought the file
was already closed.

This could happen during GC and would result in an unraisable exception.
(cherry picked from commit db68bfc771e6a85573732e0b579e8f68841c9b5c)

files:
A Misc/NEWS.d/next/Library/2025-09-09-17-57-49.gh-issue-138720.hAtsm-.rst
M Lib/test/test_io.py
M Modules/_io/bufferedio.c

diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index f3d9a5a19772f3..9741bb1e7224e5 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -2284,6 +2284,10 @@ def test_readinto(self):
                 self.assertEqual(getattr(pair, method)(data), 5)
                 self.assertEqual(bytes(data), b"abcde")
 
+        # gh-138720: C BufferedRWPair would destruct in a bad order resulting 
in
+        # an unraisable exception.
+        support.gc_collect()
+
     def test_write(self):
         w = self.MockRawIO()
         pair = self.tp(self.MockRawIO(), w)
diff --git 
a/Misc/NEWS.d/next/Library/2025-09-09-17-57-49.gh-issue-138720.hAtsm-.rst 
b/Misc/NEWS.d/next/Library/2025-09-09-17-57-49.gh-issue-138720.hAtsm-.rst
new file mode 100644
index 00000000000000..4f3f54e1deb89f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-09-09-17-57-49.gh-issue-138720.hAtsm-.rst
@@ -0,0 +1,4 @@
+Fix an issue where :class:`io.BufferedWriter` and :class:`io.BufferedRandom`
+had different definitions of "closed" for :meth:`~io.IOBase.close` and
+:meth:`~io.IOBase.flush` which resulted in an exception when close called
+flush but flush thought the file was already closed.
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index 426c6176380b14..1360e53ed5dc5d 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -552,8 +552,8 @@ _io__Buffered_close_impl(buffered *self)
     if (!ENTER_BUFFERED(self)) {
         return NULL;
     }
-
-    r = buffered_closed(self);
+    /* gh-138720: Use IS_CLOSED to match flush CHECK_CLOSED. */
+    r = IS_CLOSED(self);
     if (r < 0)
         goto end;
     if (r > 0) {

_______________________________________________
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