Python – memoryview()
Python memoryview() built-in function is used to get the memory view object that allows you to view the contents of a bytes-like object as a sequence of machine values.
memoryview() built-in function can be used for efficient data manipulation, sharing memory between objects, interacting with C code, etc.
In this tutorial, you will learn the syntax and usage of memoryview() built-in function, and cover some examples.
The syntax of memoryview() function is
|object||A bytes-like object. e.g., bytes, bytearray, or another memory view object.|
1. Get memory view of bytes object
In the following program, we take a bytes object, and get a memoryview object for this bytes object.
Run Code Copy
data = bytearray(b'hello world') # Get memory view of data mv = memoryview(data) print(mv)
<memory at 0x104725d80>
2. Slice memoryview
memoryview supports slicing. In the following program, we slice the memoryview object, and print it to standard output.
Run Code Copy
data = bytearray(b'hello world') # Get memory view of data mv = memoryview(data) # Slice memoryview mvslice = mv[2:8] print(bytes(mvslice))
Uses of memoryview()
memoryview() built-in function can be used for the following purposes.
- Efficient data manipulation: By using memoryview() on a bytes-like object, you can efficiently manipulate the data as a sequence of machine values. This can be faster than copying the data into a new object or converting it to a different data type.
- Sharing memory between objects: Since memoryview() returns a view of the data rather than a new object, it can be used to share memory between different parts of your code. For example, you could create a memory view of a large bytes-like object and pass it to a function that only needs to access a small portion of the data.
- Interacting with C code: The memoryview() function can be useful when interacting with C code that operates on raw memory. You can pass a memory view object to a C function that expects a pointer to memory, allowing you to access and manipulate the data in Python and C code.
In this Built-in Functions tutorial, we learned the syntax of the memoryview() built-in function, and how to use this function to create a memoryview for a bytes-like object.