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.
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.
mv = memoryview(obj)
obj is the object to create a
memoryview of, and
mv is the
memoryview()can only be used on objects that support the buffer protocol and have a readable or writable buffer interface, such as
numpyarrays, and other objects created using the struct module.
strobjects don’t support the buffer protocol.
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 nparr = 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 supports indexing and slicing operations:
arr = bytearray(10)mv = memoryview(arr)mv = 65print(mv)
This will output a modified element:
Here is how a slicing operation on a
memoryview object is performed:
Note that a slice of a
memoryview object is also a
<memory at 0x117003880>