Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Memoryview vs Bytearray?

When should I use memoryview in Python2.7? I just can't find any profit of using it over regular bytearray. Also memoryview doesn't support string methods, that is making it absolutely unusable. Am I wrong?

like image 237
d-d Avatar asked Oct 16 '16 10:10

d-d


1 Answers

Ok, finally, working on the network software, I found a use case for memoryviews: when we have a fixed size socket buffer and we want to perform fast slicing on it (read/write data from any given position w/o creating extra copies in memory), something like this:

buf = bytearray(4096)
mview = memoryview(buf)
socket.recv_into(mview)
print mview[256:]

So, in some cases it's handy to have a memoryview on a bytearray. The only thing you should keep in mind with such scheme: after you created a memoryview on a bytearray, you can't change the size of a bytearray, until you delete this memoryview, bytearray will be limited to its initial size and throw BufferError: Existing exports of data: object cannot be re-sized error on every attempt to add more data there.

like image 53
d-d Avatar answered Oct 09 '22 00:10

d-d