[Python-checkins] bpo-37054, _pyio: Fix BytesIO and TextIOWrapper __del__() (GH-13601)

Miss Islington (bot) webhook-mailer at python.org
Mon May 27 20:05:53 EDT 2019


https://github.com/python/cpython/commit/0f352d44e7c14c1c93e3999402c85512b9d5a6ca
commit: 0f352d44e7c14c1c93e3999402c85512b9d5a6ca
branch: 3.7
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2019-05-27T17:05:49-07:00
summary:

bpo-37054, _pyio: Fix BytesIO and TextIOWrapper __del__() (GH-13601)


Fix destructor _pyio.BytesIO and _pyio.TextIOWrapper: initialize
their _buffer attribute as soon as possible (in the class body),
because it's used by __del__() which calls close().
(cherry picked from commit a3568417c49f36860393075b21c93996a5f6799b)

Co-authored-by: Victor Stinner <vstinner at redhat.com>

files:
A Misc/NEWS.d/next/Library/2019-05-28-01-06-44.bpo-37054.sLULGQ.rst
M Lib/_pyio.py

diff --git a/Lib/_pyio.py b/Lib/_pyio.py
index afbd48e0005d..e81cc5128881 100644
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -839,6 +839,10 @@ class BytesIO(BufferedIOBase):
 
     """Buffered I/O implementation using an in-memory bytes buffer."""
 
+    # Initialize _buffer as soon as possible since it's used by __del__()
+    # which calls close()
+    _buffer = None
+
     def __init__(self, initial_bytes=None):
         buf = bytearray()
         if initial_bytes is not None:
@@ -866,7 +870,8 @@ def getbuffer(self):
         return memoryview(self._buffer)
 
     def close(self):
-        self._buffer.clear()
+        if self._buffer is not None:
+            self._buffer.clear()
         super().close()
 
     def read(self, size=-1):
@@ -1936,6 +1941,10 @@ class TextIOWrapper(TextIOBase):
 
     _CHUNK_SIZE = 2048
 
+    # Initialize _buffer as soon as possible since it's used by __del__()
+    # which calls close()
+    _buffer = None
+
     # The write_through argument has no effect here since this
     # implementation always writes through.  The argument is present only
     # so that the signature can match the signature of the C version.
diff --git a/Misc/NEWS.d/next/Library/2019-05-28-01-06-44.bpo-37054.sLULGQ.rst b/Misc/NEWS.d/next/Library/2019-05-28-01-06-44.bpo-37054.sLULGQ.rst
new file mode 100644
index 000000000000..9a2433abd0d0
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-05-28-01-06-44.bpo-37054.sLULGQ.rst
@@ -0,0 +1,3 @@
+Fix destructor :class:`_pyio.BytesIO` and :class:`_pyio.TextIOWrapper`:
+initialize their ``_buffer`` attribute as soon as possible (in the class
+body), because it's used by ``__del__()`` which calls ``close()``.



More information about the Python-checkins mailing list