memoryview#
memoryview is a zero-copy view over a bytes-like object
(bytes, bytearray, array.array, numpy array,
anything supporting the buffer protocol). Slicing produces
another view; no copy.
buf = bytearray(65536)
mv = memoryview(buf)
sock.recv_into(mv[1024:2048]) # write directly into buf
header = mv[:24] # no copy
payload = mv[24:] # no copy
Conversion to bytes happens only when the operator asks for
it (bytes(mv[:24])) or when a function copies the slice
internally.
memoryview exposes cast for reinterpreting the buffer as
a different fixed-width type, useful for treating a byte buffer
as an array of integers.
mv = memoryview(bytearray(16))
mv32 = mv.cast("I") # view as unsigned 32-bit ints
mv32[0] = 0xdeadbeef
Always release a memoryview over a bytearray before
trying to resize the buffer; the view holds a reference that
freezes the size.
buf = bytearray(b"abcdef")
mv = memoryview(buf)
try:
... # use mv
finally:
mv.release()
buf.extend(b"more") # safe now