d-d d-d - 2 months ago 46
Python Question

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?

d-d d-d

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)
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.