Python's memoryview: Slicing Bytes Without Copying

This article explains how memoryview exposes the buffer of bytes, bytearray and array objects without copying, measures copies against views, and describes writable views, casts, readinto loops and the rules that shared buffers impose.

A green snake with water droplets on its scales coiled around a diagonal branch, watching from above its loops against a dark background.
Photo by Matteo Vella on Unsplash

Slicing a bytes or bytearray object creates a new object and copies every selected byte into it, which is harmless for short strings and expensive for the megabytes of a file, an image or a network message. The present article addresses memoryview, the built-in type that exposes the memory of another object without copying it. Online games with a spectator mode offer a precise image for it: a spectator watches the same match that the players are playing, not a recorded copy, so every move appears in the spectator's window the moment it happens. In the same way, a memoryview is a window onto the buffer of an existing object, and slicing the view only moves the window. The analogy, however, stops at this point, because a spectator can never act on the match, whereas a view of a mutable object can write through the window. The article measures the cost of copies against views, shows how views share and reinterpret memory, and identifies the rules that a program holding a view must respect. A slice that costs nothing, whatever its size, is the secret weapon of this type.

Copies Versus Views

The following example slices five megabytes out of a ten-megabyte bytes object, first directly and then through a memoryview, and measures the memory each operation allocates with tracemalloc.

import tracemalloc

data = bytes(10_000_000)

tracemalloc.start()
chunk = data[1000:5_001_000]
copy_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()

tracemalloc.start()
window = memoryview(data)[1000:5_001_000]
view_peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()

print(len(chunk) == len(window))        # Output: True
print(copy_peak >= 5_000_000)           # Output: True
print(view_peak < 10_000)               # Output: True
print(bytes(window[:3]) == chunk[:3])   # Output: True

The slice allocated about five million bytes, one for each byte copied, whereas the view allocated about five hundred, the size of a small descriptor that records where the window starts and how long it is. On the test machine, with CPython 3.12, the slice took about 0.6 milliseconds and the view about 0.2 microseconds, and the difference grows with the size of the slice. The view also keeps the original object alive, through the reference counting described in the article devoted to memory management, so the buffer cannot disappear while a window onto it exists.

Writing Through a View

A view of a mutable object, such as a bytearray or an array.array, is writable, and every write lands in the shared buffer. A view of an immutable object, such as bytes, is read-only.

data = bytearray(b"Hello, Python World!")
word = memoryview(data)[7:13]

print(bytes(word))     # Output: b'Python'
word[0] = ord("J")
print(data)            # Output: bytearray(b'Hello, Jython World!')

frozen = memoryview(b"immutable")
try:
    frozen[0] = ord("I")
except TypeError as error:
    print(error)       # Output: cannot modify read-only memory

print(memoryview(data).toreadonly().readonly)  # Output: True

The assignment through word changed the bytearray itself, because the view and the array share the same bytes. Elements of a byte view are integers from 0 to 255, which is why the new value is written as ord("J"). The method toreadonly, added in Python 3.8, produces a view that can be handed to other code without granting it the right to modify the buffer.

Formats, Shapes and Casts

A view does not only expose bytes: it describes the elements of the buffer with a format code, an itemsize and a shape, taken from the exporting object. The method cast, available since Python 3.3, reinterprets the same memory with a different format.

from array import array

numbers = array("i", [1, 2, 3, 4])
view = memoryview(numbers)
print(view.format, view.itemsize, view.nbytes)  # Output: i 4 16
print(view.tolist())                           # Output: [1, 2, 3, 4]

raw = view.cast("B")
print(len(raw), raw.nbytes)                    # Output: 16 16

grid = memoryview(bytearray(range(6))).cast("B", shape=[2, 3])
print(grid.shape, grid.tolist())               # Output: (2, 3) [[0, 1, 2], [3, 4, 5]]

The four integers occupy sixteen bytes, and the cast to "B" exposes them as sixteen unsigned bytes without copying anything; the order of those bytes depends on the byte order of the machine. A cast can also add dimensions, as the 2 × 3 grid shows, which is how numerical libraries describe matrices over a flat buffer. Since Python 3.12 (PEP 688), a class written in Python can export its own buffer through the method __buffer__, and collections.abc.Buffer identifies every object that supports the protocol. Python 3.14 added the methods count and index to memoryview and made it a generic type, memoryview[int], for annotations.

Reading into a Reusable Buffer

Binary streams offer the method readinto, which fills an existing writable buffer instead of creating a new bytes object for every read. Combined with a memoryview, it processes a stream of any size with a single, fixed allocation.

import io

stream = io.BytesIO(bytes(range(10)) * 3)
buffer = bytearray(8)
view = memoryview(buffer)

total = 0
while (count := stream.readinto(view)):
    total += count
    print(count, view[:count].tolist()[:3])
# Output: 8 [0, 1, 2]
# Output: 8 [8, 9, 0]
# Output: 8 [6, 7, 8]
# Output: 6 [4, 5, 6]
print(total)  # Output: 30

The last read returns only six bytes, so the slice view[:count] limits processing to the valid part of the buffer; the remaining two bytes still hold data from the previous read. The same pattern applies to files opened in binary mode and to sockets, which also accept a memoryview in readinto and recv_into.

Pitfalls of Memory Views

Sharing memory removes copies, but it also ties the lifetime and the size of the buffer to every view that exists. Five pitfalls are distinguished, which are the following:

  1. Resizing is blocked. A bytearray with an exported view cannot change its size; append or extend raises BufferError until every view is released.
  2. Shared writes. A write through any view is visible through all the others and through the original object, which surprises code that expected an independent copy.
  3. Released views. After release(), or at the end of a with block, every operation on the view raises ValueError.
  4. Stale data in reused buffers. After a short read, the end of a reused buffer still contains old bytes; only the slice reported by the read is valid.
  5. Limited hashing. Only read-only one-dimensional views of byte formats are hashable, so a view of a bytearray cannot be a dictionary key.

The first and third pitfalls are reproduced in the following example.

data = bytearray(b"abc")
view = memoryview(data)

try:
    data.append(ord("d"))
except BufferError as error:
    print(error)  # Output (CPython 3.12): Existing exports of data: object cannot be re-sized

view.release()
data.append(ord("d"))
print(data)       # Output: bytearray(b'abcd')

with memoryview(data) as scoped:
    print(scoped[0])  # Output: 97
try:
    scoped[0]
except ValueError as error:
    print(error)  # Output: operation forbidden on released memoryview object

Releasing the view, explicitly or through the with statement described in the article devoted to context managers, returns control of the buffer to its owner, which may then resize it again.

Choosing Between Copies and Views

Consequently, a view pays off when the data is large or the same buffer is read many times, and a copy remains simpler when the slice is small or must outlive the original, as the following table summarizes.

Situation Recommended approach
Small slices, or slices that must be independent Ordinary slicing, which copies
Large binary data processed in parts memoryview slices
Reading streams, files or sockets in chunks readinto or recv_into with a reused buffer and a view
Modifying part of a bytearray in place A writable memoryview slice
Handing data to code that must not modify it view.toreadonly() or bytes
Reinterpreting raw bytes as numbers cast for native layouts; struct for explicit layouts
Buffers that must grow while being viewed Release the view first, or build a new buffer

Conclusion

It is concluded that memoryview replaces the copy made by every slice of a binary object with a window onto the same memory, which reduces the cost of a slice to a few hundred bytes and a fraction of a microsecond, whatever its length. Views can write through to mutable buffers, reinterpret elements with cast, and feed readinto loops that process streams with a single allocation. This magic requires discipline: an exported buffer cannot be resized, a released view cannot be used, and shared writes are visible everywhere. Interpreting the bytes that a view exposes, with explicit sizes and byte orders, is the task of the module struct, which is developed in a future article of this series.