Python Memoryview vs Bytearray?
Asked Answered
W

1

8

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?

Wite answered 16/10, 2016 at 10:21 Comment(0)
W
11

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.

Wite answered 4/11, 2016 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.