Memory views
A memoryview is a window onto an object's raw buffer. It lets you slice and interpret bytes without copying, as long as the object supports the buffer protocol.
Detailed Explanation
bytes, bytearray, array.array, mmap, and many NumPy arrays expose a contiguous (or strided) block of memory. memoryview(obj) wraps that block. Slicing a memoryview (view[10:20]) is another view, not a new bytes object. Casting view.cast("I") reinterprets the same memory as unsigned 32-bit integers. You pay for a copy when you call view.tobytes() or bytes(view).
This is how you parse a binary protocol without allocating a new string per field. It is also how you can corrupt a bytearray through two views at once: they share memory. A bytes memoryview is read-only (view.readonly is true). A bytearray view is writable.
The format character follows struct / array codes: "B" for unsigned bytes, "h" for signed shorts, and so on. itemsize, nbytes, shape, and strides describe the layout. A non-contiguous view (a NumPy column) still works; tobytes() then copies.
Views keep the underlying object alive. A long-lived view of a huge bytearray pins that allocation. Release it with view.release() or a with memoryview(...) as view: block when you are done, especially around mmap.
Do not use memoryview for text. Decode to str. Do not use it as a general list slice. It is a binary tool. When you need numeric arrays with arithmetic, NumPy is the usual next layer and uses the same buffer protocol underneath.
Code Examples
buf = bytearray(b"HEADERPAYLOAD")
view = memoryview(buf)
payload = view[6:] # no copy
print(bytes(payload)) # b'PAYLOAD'
payload[0] = ord("p")
print(buf) # bytearray(b'HEADERpAYLOAD')raw = bytes(range(8))
ints = memoryview(raw).cast("I") # two uint32 words, little-endian host
print(list(ints)) # platform-dependent integers
print(ints.readonly) # True, because raw is bytesdata = bytearray(b"abcdef")
with memoryview(data) as view:
print(view[2:5].tobytes()) # b'cde'Common Gotchas
Assuming a slice copied
writes through a view of a `bytearray` change the original.
Using a view after `release`
`ValueError: operation forbidden on released memoryview`.
Cast requires the length to divide evenly
`cast("I")` on 5 bytes fails. Check `nbytes`.
`bytes(view)` copies
stay in views until you need an owned `bytes` (hashing, storing, sending).