Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python memoryview() function

Reference for Python memoryview(): create a zero-copy view of bytes, bytearray or array data, slice without copying, write through the view and release it.

The memoryview() function wraps an object that supports the buffer protocol (such as bytes, bytearray or array.array) and returns a view of its memory. Slicing the view does not copy the data; it just creates a new window onto the same bytes.

That makes it valuable when you handle large binary buffers: parsing network packets, filling a buffer piece by piece, or passing slices to functions without allocating new objects. For everyday scripts you will rarely need it.

Python
data = bytearray(b"abcdef")
view = memoryview(data)
view[0] = 65
print(data)   # bytearray(b'Abcdef')

Try it

Python A view shares memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Read-only views, casting and release

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
memoryview(object)
Name Description
object An object that supports the buffer protocol, such as bytes, bytearray, array.array, or another memoryview.

Return value: a memoryview object.

Raises: TypeError if the object does not support the buffer protocol (for example a str or a list).

Usage notes

  • No copy on slicing. view[a:b] is another view; bytes(view[a:b]) or view[a:b].tobytes() makes a real copy.
  • Writable only if the source is. A view of bytes is read-only (view.readonly is True); a view of bytearray allows view[i] = value and slice assignment of the same length.
  • Resizing is blocked while a view exists. Appending to a bytearray that has an exported view raises BufferError. Call view.release() or use with memoryview(...) first.
  • Items. Indexing a byte view gives integers 0 to 255. cast() reinterprets the memory with another format such as "H" or "i" and, for multi-byte items, depends on the machine's byte order.
  • Useful attributes: nbytes, itemsize, format, shape, obj. Methods include tolist(), tobytes(), hex(), cast() and release().
  • Comparison. Views compare equal to bytes-like objects with the same content.
  • Not a string view. Text must be encoded to bytes first.
  • When it helps. Only for large data or tight loops; for small values bytes slicing is simpler and fast enough.