memoryview()
Zero-copy view over bytes-like data. Slicing a memoryview does not allocate.
Common call
mv = memoryview(buf)
Returns
a memoryview — supports slicing, indexing, iteration
Replaces
slicing bytes / bytearray, which COPIES; memoryview slices are views
Watch out
the underlying buffer must support the buffer protocol (bytes, bytearray, array, mmap, numpy...)
memoryview(objectobject — An object supporting the buffer protocol: bytes, bytearray, array.array, mmap.mmap, numpy arrays, etc. str is NOT bytes-like — encode() first.type: bytes-like · required)
→ memoryview
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | bytes-like | yes | An object supporting the buffer protocol: bytes, bytearray, array.array, mmap.mmap, numpy arrays, etc. str is NOT bytes-like — encode() first. |
Return value
memoryview — A view over the underlying object's memory buffer. Reads and slices are ZERO-COPY — no data is duplicated. Supports the buffer protocol, so C extensions can access the same memory directly.
Common patterns
Avoid copies when slicing large buffers
The whole point — memoryview lets you slice without allocating.
buf = bytearray(large_data) header = memoryview(buf)[:32] # zero-copy
Modify a bytearray through a memoryview
Writes flow through to the underlying buffer.
buf = bytearray(b"hello") mv = memoryview(buf) mv[0] = ord("H") buf # bytearray(b"Hello")
Cast to a different unit size
memoryview.cast reinterprets bytes as ints, floats, etc.
mv = memoryview(bytes([1, 0, 0, 0])) mv.cast("i")[0] # 1 (little-endian int)
Release the view
Explicit release lets the underlying buffer be resized.
mv = memoryview(buf) ... mv.release() # or use `with memoryview(buf) as mv:`
Examples
1. Basic
mv = memoryview(b"hello")
mv[0]
Returns
104 # ord("h")2. Slice is a view
mv2 = mv[1:4]
type(mv2)
Returns
<class 'memoryview'>3. To bytes
memoryview(b"hi").tobytes()
Returns
b'hi'4. Length
len(memoryview(b"hello"))
Returns
55. Iterate as ints
list(memoryview(b"ABC"))
Returns
[65, 66, 67]6. str rejected
memoryview("hello")
Returns
TypeError: memoryview: a bytes-like object is required, not str7. Write via view
buf = bytearray(b"abc"); memoryview(buf)[0] = 65; buf
Returns
bytearray(b'Abc')Pitfalls
1. str is NOT bytes-like — encode first
A common mistake for beginners coming from string slicing. memoryview needs the buffer protocol; str does not support it. Call `.encode("utf-8")` first.
str rejected
memoryview("hello")
TypeError: memoryview: a bytes-like object is required, not str
Encode first
memoryview("hello".encode("utf-8"))
valid view
2. Writes through a memoryview mutate the underlying buffer
This is what makes memoryview powerful — and dangerous if you did not expect the aliasing. `mv[0] = 65` changes the bytearray you built the view from.
Surprising alias
buf = bytearray(b"abc") mv = memoryview(buf) mv[0] = 65 # buf becomes bytearray(b"Abc")
buf mutated
Copy first if needed
buf_copy = bytearray(buf) mv = memoryview(buf_copy)
isolated
3. You cannot resize the underlying buffer while the view exists
Attempting to resize a bytearray with an outstanding memoryview raises BufferError. Release the view first (or use `with`).
Resize blocked
buf = bytearray(b"hi") mv = memoryview(buf) buf.append(0)
BufferError: Existing exports of data: object cannot be re-sized
Release first
mv.release() buf.append(0)
works
4. memoryview of bytes is READ-ONLY
bytes is immutable. A memoryview over bytes cannot be assigned to. Only mutable sources (bytearray, array.array with writable buffer, ...) allow writes through the view.
Read-only source
memoryview(b"hi")[0] = 65
TypeError: cannot modify read-only memory
Use bytearray
memoryview(bytearray(b"hi"))[0] = 65
works
When to use
Use it
- Slicing large binary buffers without copying
- Handing a buffer region to a C API (via the buffer protocol)
- Reading fixed-format binary records via cast()
- Any place a bytes / bytearray slice is a bottleneck
Reach for something else
- Small buffers or one-off reads → bytes slice is simpler
- Text data → work with str
- You need immutable data with hashability → bytes
- You do not know what "buffer protocol" means yet — often you do not need this
Notes
Complexity
O(1) construction and slicing
Return
memoryview — supports slicing, indexing, iteration, .tobytes(), .cast()
CPython impl
Objects/memoryobject.c :: memory_new
Memory
No allocation for the underlying data — just view metadata
Thread-safe
Not safe under concurrent mutation of the underlying buffer
FAQ
When copying would be expensive — large buffers where you slice or hand off sub-regions. If you are working with small data or one-off reads, plain bytes / bytearray is simpler.
History
2.7
memoryview introduced.
3.3
.cast() method added for reinterpreting the buffer as different unit types.