PREP WITH PROOF
Menu
PYTHON & BINARY DATA / PRACTICAL GUIDE

Python memoryview vs Bytes Copy: Slices and BufferError

See when memoryview shares bytes, why read-only views still change, and how to release slices before resizing a bytearray. Five runnable Python examples.

THE QUICK ANSWER

A memoryview slice borrows the exporter’s storage. Use tobytes() when you need an independent snapshot. A read-only view can still observe writes through other references, and a live child view can keep a bytearray from resizing even after its parent view is released.

The slice that changed after you saved it

You split a packet into a header and payload, keep the payload, and reuse the receive buffer for the next packet. Later the saved payload has different bytes. In another version of the same program, extending that buffer raises BufferError. These symptoms are related: a memoryview slice still refers to storage owned by the original object.

Choose between borrowing and owning before choosing syntax. Borrow a view for a short operation that can use the original storage. Copy when a result must survive buffer reuse, pass to a consumer with stricter layout requirements, or represent a stable snapshot. Making a view read-only changes its write permissions; it does not make the original storage immutable.

The examples below were executed on CPython 3.12.14. Run them independently with the standard library. They check observed values and errors rather than making a timing or memory savings claim.

Compare a bytearray slice with a memoryview slice

For this bytearray example, ordinary slicing creates a separate bytearray. Slicing a memoryview creates another view. Both windows start with the same bytes, but a later write through the view reaches the original bytearray. A call to tobytes() captures the contents at that moment as immutable bytes.

The example keeps two forms of independent storage: copied_slice is a mutable bytearray copy, while saved is an immutable bytes snapshot. Neither is updated when the underlying buffer changes. The two live views do see those changes because they overlap. Treat a writable view as another reference with permission to edit that region.

OperationShares the original storage in this example?Use it when
data[1:4] on a bytearrayNoYou want an independent mutable slice
memoryview(data)[1:4]YesThe consumer can borrow a window
view.toreadonly()YesThis consumer should not write through its view
view.tobytes()NoYou need a stable bytes value
data = bytearray(b"abcdef")
copied_slice = data[1:4]

with memoryview(data) as whole, whole[1:4] as window:
    saved = window.tobytes()
    window[0] = ord("X")
    assert data == b"aXcdef"
    assert bytes(window) == b"Xcd"
    assert copied_slice == b"bcd"
    assert saved == b"bcd"
    whole[2:4] = b"YZ"
    assert bytes(window) == b"XYZ"

Source: Python: memoryview slicing, read-only views and release ↗

Read-only describes the view, not the lifetime of its bytes

A view of immutable bytes is read-only. You can also make a read-only view of a writable object with toreadonly(). That second case protects against writes through the returned view, but the owner and other writable references can still change the underlying bytes. The following test observes exactly that distinction.

Use a read-only view to express a borrowing contract when the producer controls the lifetime. If you place the result in a queue, return it to a caller that may keep it, or compare it later against a checksum, decide whether you need immutable contents. A read-only view of a reused bytearray cannot supply that guarantee by itself. Copy before handing off when ownership matters.

data = bytearray(b"abcd")
with memoryview(data) as writable, writable.toreadonly() as reader:
    assert reader.readonly
    snapshot = reader.tobytes()
    try:
        reader[0] = ord("Z")
    except TypeError:
        pass
    else:
        raise AssertionError("read-only view accepted a write")
    data[0] = ord("Z")
    assert bytes(reader) == b"Zbcd"
    assert snapshot == b"abcd"

Source: Python: memoryview slicing, read-only views and release ↗

A child slice can keep bytearray resizing blocked

An exported buffer must remain available while consumers hold views. For a bytearray, growing or shrinking it while an export is active can raise BufferError. Changing existing bytes without changing the length is a different operation. This is why a buffer update by index may work even when extend fails.

Releasing a parent view does not release a separate child slice. The child in this test still reads the shared bytes and still blocks resizing. Release the child when its use is over, then resize. Prefer a with block or an explicit finally clause at the boundary where you borrow the view. A context manager cleans up its own view, so avoid letting a child escape that scope by accident.

When a resize fails in a larger pipeline, trace views held in variables, queues, parser results, and any helper that returns a subview. Replacing the original variable with a new bytearray will not move old views to that new storage. If a downstream consumer must keep the data, return an owned slice instead of extending the lifetime of the reusable buffer.

data = bytearray(b"abcd")
parent = memoryview(data)
child = parent[1:3]
parent.release()

try:
    assert child.tobytes() == b"bc"
    data[1] = ord("X")  # same-length edit is allowed
    assert child.tobytes() == b"Xc"
    try:
        data.extend(b"!")
    except BufferError:
        pass
    else:
        raise AssertionError("resize unexpectedly succeeded")
finally:
    child.release()

data.extend(b"!")
assert data == b"aXcd!"

Source: Python: memoryview slicing, read-only views and release ↗

A view can be valid and still be non-contiguous

The buffer protocol describes the element format and layout as well as access to bytes. A step of two creates a view that skips positions in the source. Its logical contents can be converted to bytes, but an API that expects consecutive memory cannot necessarily consume the stepped view directly. The following struct example fails on the stepped input and succeeds on the packed copy.

Check the consumer’s contract when a view works in one library but fails in another. For a typed view, len() is not a general byte count; use nbytes when you need the size of the logical data in bytes, and check format, itemsize and contiguity separately. Casting a view can reinterpret compatible layouts, but it is not a general way to make a strided layout contiguous or decode a wire format.

import struct

with memoryview(b"abcdef") as raw, raw[::2] as alternate:
    assert alternate.nbytes == 3
    assert not alternate.c_contiguous
    try:
        struct.unpack_from("!H", alternate)
    except BufferError:
        pass
    else:
        raise AssertionError("expected a contiguity error in CPython")
    packed = alternate.tobytes()
    assert packed == b"ace"
    assert struct.unpack_from("!H", packed) == (0x6163,)

Source: Python: buffer protocol, format and contiguity ↗

Borrow for parsing and copy at the ownership boundary

This parser receives one complete frame: a one-byte kind, a two-byte unsigned big-endian length, and exactly that many payload bytes. It accepts bytes or bytearray so byte offsets are unambiguous. It reads the header directly from the view with Struct.unpack_from(), checks the length and a small application limit, then takes an owned bytes snapshot of the payload.

The returned value can outlive the input and the caller can reuse or resize its bytearray immediately. Notice that the function does not promise to avoid every copy: it avoids slicing out a separate header, then copies the part it deliberately gives away. It also does not read a socket or assemble a stream. Use the related message-framing guide when a read can contain less or more than a single frame.

The sample covers empty payloads, truncated headers and bodies, extra bytes, and an excessive declared length. If another thread can mutate the input while this function runs, coordinate access or provide a stable input before parsing. A borrowed view does not make concurrent reads and writes consistent.

import struct

HEADER = struct.Struct("!BH")
MAX_PAYLOAD = 4096

def parse_frame(buffer):
    if not isinstance(buffer, (bytes, bytearray)):
        raise TypeError("expected bytes or bytearray")
    with memoryview(buffer) as frame:
        if len(frame) < HEADER.size:
            raise ValueError("incomplete header")
        kind, length = HEADER.unpack_from(frame)
        if length > MAX_PAYLOAD:
            raise ValueError("payload exceeds limit")
        if len(frame) != HEADER.size + length:
            raise ValueError("frame length mismatch")
        with frame[HEADER.size:] as payload:
            return kind, payload.tobytes()

incoming = bytearray(HEADER.pack(7, 3) + b"abc")
kind, saved = parse_frame(incoming)
incoming[HEADER.size] = ord("X")
incoming.extend(b"!")  # the parser released both views
assert (kind, saved) == (7, b"abc")
assert parse_frame(HEADER.pack(2, 0)) == (2, b"")

for bad in (b"\x00", HEADER.pack(1, 3) + b"ab",
            HEADER.pack(1, 0) + b"x", HEADER.pack(1, 4097)):
    try:
        parse_frame(bad)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid frame accepted")

Source: Python: struct unpack_from and byte order ↗

Find the copy that already happened upstream

Check where the view was created. If you write memoryview(data[start:stop]) for a bytearray, Python evaluates the slice first. The view then borrows the already copied slice rather than the original buffer. Construct the view over data and slice the view instead when you intend to borrow the original window. The same review applies when a helper converts an input to bytes before calling a decoder.

A receive loop with a reusable buffer also needs an explicit count of how many bytes were filled. A view of the full allocation includes capacity the current read did not write. Pass only the valid window to the immediate consumer. If that consumer needs to hold it while the next read overwrites the buffer, copy the valid bytes first or give the consumer a buffer that will not be reused until it returns ownership.

For a change intended to reduce allocations, measure the whole path. A downstream decoder may need packed storage or may produce an independent value, so eliminating an early slice does not prove that the pipeline is copy-free. Keep the mutation and resize checks alongside any performance measurement so a faster implementation cannot silently change ownership.

Decide what the caller may keep

A synchronous checksum or field decoder that finishes before the buffer is reused can often take a borrowed view. A queued message, cached value, or result returned across an ownership boundary usually needs an independent copy. For a long-lived small slice of a large buffer, the copy can also let you stop retaining the larger exporter sooner.

If you choose borrowing, document when the view becomes unusable and who releases it. If you choose copying, copy only the required region and make the transfer visible in the API. Test the distinction by mutating the owner after the operation and by attempting the next resize. Those checks expose lifetime bugs that a test comparing only the initial bytes will miss.

KEEP THESE THREE THINGS

Your next steps

  1. Borrow for short operations that respect the exporter’s lifetime.
  2. Release all live views before resizing an exported bytearray.
  3. Use a copy when the consumer needs stable bytes or a compatible contiguous layout.

Sources & official resources

Linked resources checked on 2026-11-08. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →