BytesIO manages its own memory and copies the buffer used to initialize it. You can encapsulate your bytearray in a file-like class. Or you can go the other way, allowing you to allocate a BytesIO memory BytesIO . Then you can get an idea of ββthe buffer, which can be changed by index and slice, but you cannot change the size of the buffer during the presentation:
>>> f = io.BytesIO(b'abc') >>> view = f.getbuffer() >>> view[:] = b'def' >>> f.getvalue() b'def' >>> view[3] = b'g' IndexError: index out of bounds >>> f.seek(0, 2) >>> f.write(b'g') BufferError: Existing exports of data: object cannot be re-sized >>> del view >>> f.write(b'g') >>> f.getvalue() b'defg'
Edit:
See issue 22003 , BytesIO copy-on-write. The latest patch (cow6) only supports copy-on-write for bytes only.
source share