memoryview()

AndreiChernovJr's avatar
Published Aug 26, 2023
Contribute to Docs

The memoryview() built-in function creates a memoryview object that allows Python code to access the internal data of an object’s buffer without making a copy of it.

The memoryview class offers large performance gains when operating on large objects since it doesn’t create a copy when slicing. However using it requires good knowledge of the structure and format of the data in the source object.

Syntax

mv = memoryview(obj)

Where obj is the object to create a memoryview of, and mv is the memoryview created.

Note: memoryview() can only be used on objects that support the buffer protocol and have a readable or writable buffer interface, such as byte, bytearray, array.array, numpy arrays, and other objects created using the struct module. list and str objects don’t support the buffer protocol.

Example 1

The example below illustrates the creation of memoryview objects, their display, and the outcome when an inappropriate object is passed to the function:

l = [1, 2, 3, 4, 5, 6]
memoryview(l)

The output will be:

TypeError: memoryview: a bytes-like object is required, not 'list'

The following code snippet demonstrates how a memoryview object is created from a NumPy array:

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
memoryview(arr)

This will print the following output:

<memory at 0x117003700>

Note: The memory address generated will vary for each execution of the code. This discrepancy is related to the creation of a new memoryview object.

Example 2

memoryview supports indexing and slicing operations:

arr = bytearray(10)
mv = memoryview(arr)
mv[0] = 65
print(mv[0])

This will output a modified element:

65

Here is how a slicing operation on a memoryview object is performed:

print(mv[1:4])

Note that a slice of a memoryview object is also a memoryview object:

<memory at 0x117003880>

All contributors

Contribute to Docs

Learn Python on Codecademy