I read buffer of data from somewhere to bytearray. Now, I want to work with this data using stream-like interface (i.e. read, seek etc.)
Can I just wrap my bytearray with io.BytesIO?
mybytearray = bytearray(...)
stream = io.BytesIO(mybytearray)
My fear here is BytesIO copies data of mybytearray, but I don’t want it – since buffer is very big. I don’t want copies, I want the stream to work on original data and can modify it too. What can be done?
BytesIOmanages its own memory and will copy a buffer used to initialize it. You could encapsulate yourbytearrayin a file-like class. Or you can go the other way, letting theBytesIOobject handle memory allocation. Then you can get a view of the buffer that can be modified by index and slice, but you can’t re-size the buffer while the view exists:Edit:
See issue 22003,
BytesIOcopy-on-write. The latest patch (cow6) supports copy-on-write forbytesonly.