diff -r 33db20c8537c Doc/library/io.rst --- a/Doc/library/io.rst Sat Jan 31 02:45:12 2015 -0800 +++ b/Doc/library/io.rst Sat Jan 31 15:11:19 2015 +0200 @@ -599,13 +599,16 @@ than raw I/O does. .. note:: As long as the view exists, the :class:`BytesIO` object cannot be - resized. + resized or closed. .. versionadded:: 3.2 .. method:: getvalue() - Return :class:`bytes` containing the entire contents of the buffer. + Return :class:`bytes` containing the entire contents of the buffer at any + time before the :class:`BytesIO` object's :meth:`close` method is + called. + .. method:: read1() diff -r 33db20c8537c Lib/_pyio.py --- a/Lib/_pyio.py Sat Jan 31 02:45:12 2015 -0800 +++ b/Lib/_pyio.py Sat Jan 31 15:11:19 2015 +0200 @@ -852,8 +852,14 @@ class BytesIO(BufferedIOBase): def getbuffer(self): """Return a readable and writable view of the buffer. """ + if self.closed: + raise ValueError("getbuffer on closed file") return memoryview(self._buffer) + def close(self): + self._buffer.clear() + super().close() + def read(self, size=None): if self.closed: raise ValueError("read from closed file") diff -r 33db20c8537c Lib/test/test_memoryio.py --- a/Lib/test/test_memoryio.py Sat Jan 31 02:45:12 2015 -0800 +++ b/Lib/test/test_memoryio.py Sat Jan 31 15:11:19 2015 +0200 @@ -399,14 +399,19 @@ class BytesIOMixin: # raises a BufferError. self.assertRaises(BufferError, memio.write, b'x' * 100) self.assertRaises(BufferError, memio.truncate) + self.assertRaises(BufferError, memio.close) + self.assertFalse(memio.closed) # Mutating the buffer updates the BytesIO buf[3:6] = b"abc" self.assertEqual(bytes(buf), b"123abc7890") self.assertEqual(memio.getvalue(), b"123abc7890") - # After the buffer gets released, we can resize the BytesIO again + # After the buffer gets released, we can resize and close the BytesIO + # again del buf support.gc_collect() memio.truncate() + memio.close() + self.assertRaises(ValueError, memio.getbuffer) class PyBytesIOTest(MemoryTestMixin, MemorySeekTestMixin, diff -r 33db20c8537c Misc/NEWS --- a/Misc/NEWS Sat Jan 31 02:45:12 2015 -0800 +++ b/Misc/NEWS Sat Jan 31 15:11:19 2015 +0200 @@ -313,6 +313,9 @@ Library - Issue #21793: Added http.HTTPStatus enums (i.e. HTTPStatus.OK, HTTPStatus.NOT_FOUND). Patch by Demian Brecht. +- Issue #23099: Closing io.BytesIO with exported buffer is rejected now to + prevent corrupting exported buffer. + - Issue #23093: In the io, module allow more operations to work on detached streams. diff -r 33db20c8537c Modules/_io/bytesio.c --- a/Modules/_io/bytesio.c Sat Jan 31 02:45:12 2015 -0800 +++ b/Modules/_io/bytesio.c Sat Jan 31 15:11:19 2015 +0200 @@ -777,6 +777,7 @@ PyDoc_STRVAR(close_doc, static PyObject * bytesio_close(bytesio *self) { + CHECK_EXPORTS(self); reset(self); Py_RETURN_NONE; }