Programming · free software · the open webSubscribe via RSS

A Python memoryview keeps storage alive, not unchanged

A memoryview avoids a copy by sharing an exporter’s buffer. That means its lifetime, mutability and snapshot semantics are separate questions—and a read-only view is not an immutable snapshot.

A view is an agreement to share storage

A memoryview is often introduced as a way to avoid copying bytes. That description is accurate but incomplete: it is a view over an object that exports the buffer protocol. The exporter continues to own the underlying storage, while the view exposes an interpretation of some or all of it. Keeping the view alive keeps the buffer relationship active; it does not turn the storage into an independent value. [1] [2]

For a bytearray, the difference is easy to see. Start with data = bytearray(b"cat") and view = memoryview(data). Assigning view[0] = ord("b") changes data to bytearray(b"bat"). The view and the bytearray are two ways to reach the same mutable bytes. Code that passes a view to another function has shared access to storage, not delivered a frozen message.

Read-only describes the handle, not the underlying object

Calling view.toreadonly() produces a view that refuses writes made through that view. It does not make the bytearray read-only. If another part of the program retains the original bytearray, that code can still change it, and the read-only view will observe the new contents. Python’s documentation demonstrates this directly: a write through the original writable view appears when the read-only view is read afterward. [1]

This is an authority distinction. A read-only view narrows what one recipient may do using that particular reference. It does not revoke other references, establish exclusive access, or promise that the values stay constant. If an API promises “the bytes as they were when the call began,” a read-only view alone does not meet that contract. The contract must instead rely on immutable input, controlled ownership, synchronization, or a copy.

The export lifetime has practical consequences

Sharing also constrains the exporter. A bytearray cannot be resized while a memoryview exports its buffer; changing its length could relocate or invalidate storage that a consumer is using. The view therefore affects operations on the owner even when nobody writes through the view. Once the view is no longer needed, release() ends that view’s access and removes the restriction associated with it. A with memoryview(data) as view: block gives the borrowing interval an explicit boundary. [1]

The C buffer protocol formalizes the same obligation for extension types: an exporter must keep the memory described by an acquired buffer valid until the consumer releases it. This is why a custom exporter cannot hand out a pointer and then freely reallocate its backing storage. The Python-level view manages that acquire/release relationship for ordinary callers; extension code using the C API has to honor it explicitly. [2]

A copy changes the contract

When the consumer needs stable value semantics rather than shared access, make that choice visible. snapshot = bytes(view) or snapshot = view.tobytes() creates a new immutable bytes object containing the view’s data. Later changes to the original bytearray do not change that copy. The cost is memory and copying time, which is precisely what a view avoids. [1]

This gives an API designer a useful vocabulary. Accept a bytes-like object and borrow a view when the operation is short-lived and shared mutation is allowed or controlled. Copy at the boundary when queued work, caching, hashing or delayed processing needs a value that will not change under the consumer. A checksum computed over a live mutable view is a statement about the bytes observed during that computation; a cached checksum paired with a later-mutated buffer can describe different data.

A view is not necessarily a flat byte string

The buffer protocol can describe elements larger than one byte, multidimensional shapes, and non-contiguous strides. For an array.array, len(view) counts elements, while view.nbytes reports the represented byte size. Slicing may produce a view over every other element rather than a contiguous region. A consumer that assumes “view means pointer plus byte length” can therefore misread the format or layout. [1] [2]

Before handing a view to lower-level code, decide what it needs: a writable or read-only buffer, contiguous bytes, a particular element format, or a shaped array. If the next layer needs a portable serialized representation, explicitly convert or pack it. If it is designed to consume the buffer protocol, preserve the shape, format and lifetime requirements rather than silently flattening them.

Choose borrowing or snapshotting deliberately

The useful question is not simply whether a memoryview is faster. Ask what the receiver is allowed to observe and for how long. A short-lived parser can borrow a view and release it promptly, minimizing allocation. A background task that expects its input to remain fixed should receive immutable bytes or another ownership-controlled representation. A read-only view can be a good capability for preventing writes through one path, but it is not a substitute for a snapshot or a concurrency policy.

That distinction keeps a zero-copy optimization from changing an API’s meaning. Sharing storage is a resource and a contract: the exporter must keep it valid, the consumer must respect its layout, and both sides must understand whether the contents may change.

References

  1. Python built-in types documentation: memoryview
  2. Python C API: Buffer Protocol

Suggest a correction · All posts