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.
data = bytearray(b"abcdef") view = memoryview(data) view[0] = 65 print(data) # bytearray(b'Abcdef')
Try it
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.
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
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])orview[a:b].tobytes()makes a real copy. - Writable only if the source is. A view of
bytesis read-only (view.readonlyisTrue); a view ofbytearrayallowsview[i] = valueand slice assignment of the same length. - Resizing is blocked while a view exists. Appending to a
bytearraythat has an exported view raisesBufferError. Callview.release()or usewith 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 includetolist(),tobytes(),hex(),cast()andrelease(). - 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
bytesslicing is simpler and fast enough.