how to get bytes from bytearray without copying

Juraj Ivančić juraj.ivancic at
Mon Mar 3 09:52:25 CET 2014

On 3.3.2014. 1:49, Mark Lawrence wrote:

> If your data is readonly why can't you simply read it as bytes in the
> first place?  Failing that from
> tobytes() - Return the data in the buffer as a bytestring. This is
> equivalent to calling the bytes constructor on the memoryview.
>   >>> m = memoryview(b"abc")
>   >>> m.tobytes()
> b'abc'
>   >>> bytes(m)
> b'abc'

Initially it has to be a bytearray because I read this data from a 
socket. My point is that once I have a bytearray x, then

m = memoryview(bytes(x))

is a very expensive way to make a read-only memoryview, opposed to

m = memoryview(x)

or (fictional)

m = memoryview(x, force_readonly=True)

especially if the x-es are many, large, and occur often.

I feel like memoryview's __hash__ is trying to be to smart for its own 
good, and that it should just return the damn hash like its name 
suggests, regardless of the value of 'writable' flag.

More information about the Python-list mailing list