how to get bytes from bytearray without copying

Cameron Simpson cs at zip.com.au
Sun Mar 2 19:44:58 EST 2014


On 03Mar2014 01:07, Juraj Ivančić <juraj.ivancic at gmail.com> wrote:
> 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

Have you considered subclassing memoryview and giving the subclass
a __hash__ method?

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

Mountain rescue teams insist the all climbers wear helmets, and fall haedfirst.
They are then impacted into a small globular mass easily stowed in a rucsac.
        - Tom Patey, who didnt, and wasnt



More information about the Python-list mailing list