Python memoryview()
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 asbyte,bytearray,array.array,numpyarrays, and other objects created using the struct module.listandstrobjects 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 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
memoryviewobject.
Example 2
memoryview supports indexing and slicing operations:
arr = bytearray(10)mv = memoryview(arr)mv[0] = 65print(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>
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours