Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Numbers and Binary Data

Python memoryview in depth

Guide to Python memoryview objects: slice bytes and arrays without copying, cast formats, tolist(), release(), readonly buffers and the exported-buffer resize trap.

A memoryview is a window onto the memory of another object that supports the buffer protocol: bytes, bytearray, array.array, NumPy arrays and others. Slicing a bytes object copies the data; slicing a memoryview creates another view of the same memory, so even a multi-gigabyte buffer can be cut into pieces instantly.

Because a view over a bytearray is writable, you can also change the underlying data through it. Views are the right tool for parsing binary formats, socket buffers and large files when copies would be wasteful. The basic constructor is on the memoryview() reference page; this page covers how the objects behave.

Python
data = bytearray(b"hello world")
view = memoryview(data)
view[:5] = b"HELLO"
bytes(data)       # b'HELLO world'

Try it

Python Views share 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 cast(), arrays 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.

Key members

Member Description
mv[i], mv[a:b] An item (an int for format "B") or a new view; slicing does not copy.
mv.tobytes() / bytes(mv) Copy the viewed data into a new bytes.
mv.tolist() Convert items to a list of numbers (nested lists for multi-dimensional views).
mv.cast(format, shape=None) A new view with another item type or shape. Only to or from byte formats ("B", "b", "c").
mv.readonly True if writes are refused.
mv.format, mv.itemsize, mv.nbytes, mv.shape, mv.ndim Describe the element type and layout.
mv.release() Detach from the source object. Any later use raises ValueError.
mv.obj The object being viewed.

Raises: TypeError for objects without a buffer or writes on a read-only view; ValueError after release(), for a bad cast or a size mismatch on slice assignment; BufferError on the source object when it would be resized while views exist.

Usage notes

  • No copy, but not free. Creating a view costs a small object; use it when the buffer is large or sliced many times. For small data plain bytes is simpler.
  • Slice assignment needs equal sizes. view[0:2] = b"abc" raises ValueError because the view cannot grow.
  • Resizing is blocked. While a memoryview of a bytearray exists, appending or deleting raises BufferError. Release the view, use a with block, or let it be garbage collected first.
  • Views keep the source alive, so a tiny slice can pin a huge buffer in memory. Convert to bytes if you only need a small part for long.
  • Hashing. A read-only memoryview with format "B", "b" or "c" is hashable and compares equal to the same bytes; writable views are not hashable.
  • Reading files without copies: readinto() on a binary file or socket fills a preallocated bytearray through a view: f.readinto(view[offset:]).
  • Multi-dimensional support is limited. It handles shapes and strides for C-contiguous data, but NumPy is the right tool for real array math.