memoryview() is a built-in Python type that creates a memory-efficient, zero-copy view into the internal buffer of a binary object — exposing it as a sequence of bytes or packed data without duplicating memory. In 2026, memoryview remains a critical tool in performance-sensitive domains: data science (large binary arrays, image processing), systems programming (socket I/O, file mmap), cryptography (buffer manipulation), and high-throughput pipelines — enabling fast slicing, casting, and in-place modifications on bytes, bytearray, array.array, NumPy buffers, and more, all while avoiding unnecessary copies.
Here’s a complete, practical guide to using memoryview() in Python: creation & basic slicing, casting & formats, real-world patterns (earthquake binary signal processing, zero-copy parsing, efficient I/O), and modern best practices with type hints, performance, safety, and integration with NumPy/Dask/bytes/bytearray/array/mmap/socket.
Basic memoryview() creation & slicing — zero-copy access to buffers.
# From bytearray (mutable)
ba = bytearray(b"Hello, world!")
mv = memoryview(ba)
print(mv) #
print(mv.tobytes()) # b'Hello, world!'
print(mv[0]) # 72 (ord('H'))
print(bytes(mv[0:5])) # b'Hello' (slice view)
# Modify through memoryview (affects original bytearray)
mv[0] = ord('J')
print(ba) # bytearray(b'Jello, world!')
# From bytes (immutable)
b = b"Immutable"
mv_bytes = memoryview(b)
print(mv_bytes[0]) # 73 (ord('I'))
# mv_bytes[0] = 74 # TypeError: cannot modify read-only memoryview
Casting & format strings — reinterpret buffer as different types (struct-like).
import struct
import array
# Float32 array as bytes
floats = array.array('f', [1.5, 2.718, 3.14159])
mv_floats = memoryview(floats)
# Cast to bytes view
mv_bytes = mv_floats.cast('B') # 'B' = unsigned char
print(mv_bytes.tolist()[:8]) # first 8 bytes
# Cast back to float32
mv_cast = mv_bytes.cast('f')
print(mv_cast.tolist()) # [1.5, 2.718, 3.14159]
# Packed struct example
data = struct.pack('>if', 42, 3.14) # int + float big-endian
mv = memoryview(data)
int_val = mv.cast('i')[0] # first 4 bytes as int
float_val = mv.cast('f', offset=4)[0]
print(int_val, float_val) # 42 3.14
Real-world pattern: zero-copy processing of large earthquake binary signals.
import numpy as np
# Simulated large binary acceleration data (float32 time series)
raw_data = np.random.randn(1_000_000).astype(np.float32).tobytes()
# Create memoryview (zero-copy)
mv = memoryview(raw_data)
# Cast to float32 array view
accel = np.frombuffer(mv, dtype=np.float32)
# Compute stats without copying
print(f"Mean acceleration: {accel.mean():.4f}")
print(f"Max abs: {np.abs(accel).max():.4f}")
# Modify in-place via memoryview (if source is bytearray)
ba = bytearray(raw_data)
mv_ba = memoryview(ba)
mv_ba.cast('f')[0] = 999.0 # first value changed
print(np.frombuffer(mv_ba, dtype=np.float32)[0]) # 999.0
Best practices for memoryview() in Python & data workflows. Use memoryview for zero-copy — when slicing or casting large binary buffers (sockets, files, NumPy arrays). Modern tip: use NumPy np.frombuffer(mv, dtype) — preferred for numeric data; Polars/Dask for tabular binary columns. Prefer memoryview over slicing bytes — avoids data copy: mv[100:200] is view, bytes[100:200] copies. Use cast(format, shape=None, offset=0) — reinterpret as different types (B, b, h, i, f, d, etc.). Add type hints — def process_buffer(mv: memoryview) -> None. Use mv.release() — explicit release (rarely needed). Use mv.tobytes() — materialize view to bytes. Use mv.tolist() — convert to list of ints. Use len(mv) — buffer length in bytes. Use mv.readonly — check if view is read-only. Use mv.format — current format character. Use mv.itemsize — size of each element in bytes. Use mv.nbytes — total bytes in view. Use mv.ndim / mv.shape — after cast with shape. Use mv.strides — memory strides. Use mv.suboffsets — for indirect buffers. Use memoryview(b'abc') — from bytes literal. Use memoryview(bytearray(b'abc')) — mutable view. Use memoryview(array.array('i', [1,2,3])) — from array module. Use memoryview(np.array(...)) — from NumPy array. Use socket.recv_into(mv) — zero-copy receive. Use file.readinto(mv) — zero-copy file read. Use mv.cast('B') — to byte view. Use mv.cast('f', shape=(n,)) — to float array view. Use mv.hex() — hex representation (Python 3.5+).
memoryview(obj) creates a zero-copy view into a binary buffer — supports slicing, casting, in-place modification (if mutable source), and high-performance operations on bytes/bytearray/array/NumPy buffers. In 2026, use for efficient I/O, binary parsing, signal processing, and integrate with NumPy/Dask for numeric views. Master memoryview, and you’ll handle large binary data with minimal memory overhead and maximum speed.
Next time you need to slice or reinterpret binary data without copying — use memoryview(). It’s Python’s cleanest way to say: “Give me a window into this buffer — zero-copy, fast, and flexible.”