how to get bytes from bytearray without copying

Cameron Simpson cs at
Mon Mar 3 01:44:58 CET 2014

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

Cameron Simpson <cs at>

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