The memoryview() function is a built-in function that returns a memoryview object, which can be used to access binary data in Python.

Function Syntax

memoryview(obj)

Parameters:

  • obj: An object supporting the buffer protocol, such as bytes, bytearray, array.array, etc.

The returned memoryview object provides an interface similar to bytearray objects, but it's not a truly mutable sequence—it's a read-only view that can access the memory of the original object.

When working with binary data, such as audio, video, or image files, using the memoryview() function can improve processing efficiency because it allows direct access to the raw data's memory without creating temporary copies.

memoryview() Function Examples

Here are some simple examples demonstrating how to use the memoryview() function to access binary data:

# Create a bytes object containing binary data
data = bytes([0x10, 0x20, 0x30, 0x40])

# Create a memoryview object
view = memoryview(data)

# Access contents of memoryview object
print(view[0])    # Output: 16
print(view[1])    # Output: 32
print(view[2])    # Output: 48
print(view[3])    # Output: 64

view2 = memoryview(b'abcefg')
print(view2[0])   # Output: 97
print(view2[1])   # Output: 98
# Use slicing for access
print(view2[1:4]) # Output: <memory at 0x0000021D34B9E7C0>

If the underlying object is writable, memoryview supports one-dimensional slice assignment, but resizing is not allowed:

data = bytearray(b'abcefg')
view = memoryview(data)
print(view.readonly)
view[0] = ord(b'z')
view[1:3] = b'xx'
# view[1:3] = b'kkk' # Not allowed, length mismatch
print(data)

Program Output

False
bytearray(b'zxxefg')

Performance of memoryview

Difference from slice access:

# Traditional way: slicing creates new data copies
data = bytearray(b'Hello World')
slice1 = data[0:5]  # Creates new bytearray copy
slice1[0] = 90      # Modifies only the copy, not original data

# Using memoryview: zero-copy access
mv = memoryview(data)
slice2 = mv[0:5]    # No data copy, directly accesses original buffer
slice2[0] = 90      # Directly modifies original data
print(data)         # bytearray(b'Zello World')

memoryview Object

memoryview provides several commonly used methods and properties:

.tobytes() Method

Returns the data in the buffer as a bytes string. Equivalent to calling the bytes constructor on memoryview:

view = memoryview(b'abcdefg')
print(view.tobytes())  # Output: b'abcdefg'
print(bytes(view))     # Output: b'abcdefg'

.hex() Method

Returns a string object with two hex digits per byte in the buffer:

view = memoryview(b'abcdefg')
print(view.hex())  # Output: 61626364656667

.tolist() Method

Returns the data in the buffer as a list of elements:

view = memoryview(b'abcdefg')
print(view.tolist())  # Output: [97, 98, 99, 100, 101, 102, 103]

.toreadonly() Method

Returns a read-only version of the memoryview object. The original memoryview object is not changed:

view = memoryview(b'abcdefg')
view2 = view.toreadonly()
view2[1:3] = b'xx'  # TypeError: cannot modify read-only memory

.release() Method

Releases the underlying buffer of the memoryview object:

view = memoryview(b'abcdefg')
view.release()
print(view[0])  # ValueError: operation forbidden on released memoryview object

Using with statement achieves similar effect through context management protocol:

with memoryview(b'abcdefg') as view:
    print(view[0])  # Output: 97

print(view[0])  # ValueError: operation forbidden on released memoryview object

readonly Property

Whether it's read-only depends on the underlying object:

v1 = memoryview(bytes(b'abcdefg'))
print(v1.readonly)  # True
v2 = memoryview(bytearray(b'abcdefg'))
print(v2.readonly)  # False

nbytes Property

Get total number of bytes:

view = memoryview(bytes(b'abcdefg'))
print(view.nbytes)  # 7

itemsize Property

Get bytes per element.