how to get bytes from bytearray without copying

  • Thread starter Juraj Ivanèiæ
  • Start date
J

Juraj Ivanèiæ

Is it possible to somehow 'steal' bytearray's buffer and make it a
read-only bytes? I failed to find a way to do this, and would like to
make sure.

My use case is, I would expect, fairly common. I read a certain
(potentially very large) amount of data from the network into a
pre-allocated bytearray. From that point on, this data is logically
read-only. To prevent making redundant copies, I wrap it in a
memoryview, and then slice and dice it. The problem with this memoryview
is that it, and its slices, are considered writable, and thus cannot be
hashed:

ValueError: cannot hash writable memoryview object

The only way (AFAICT) to make this work is to first create a bytes
object from bytearray, but this copies the data. I don't need this copy,
so I'd like to avoid it, because of both principle and performance reasons.

Is there any reason why bytearray isn't able to release/convert its
buffer to bytes? I see that it has a clear() method which... well...
clears it. The former would be much more useful.

I would also be content if there is some way of making memoryview
artificially read-only to avoid the above error.

Any help/thoughts/comments are highly appreciated.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top