The memoryview function in Python generates a memoryview object based on the specified argument. Prior to delving into memoryview, it is essential to familiarize ourselves with Python's Buffer Protocol.
The Buffer Protocol offers a mechanism for accessing the internal data of an object. This internal data typically consists of a memory array or a buffer. It enables a given object to expose its internal data (buffers) while allowing other entities to access these buffers directly, eliminating the need for intermediate copying.
Access to this functionality is limited to the C-API and is not available through our standard code base. To enable access to the same protocol within the regular Python code base, Python provides memory views. Memory View objects facilitate the ability for Python code to interact with the internal buffers of an object by generating a memory view object.
Python memoryview Function Syntax
It has the following syntax:
memoryview(obj)
Parameters
- obj: This refers to an object whose internal data requires processing. The obj must be compatible with the buffer protocol, meaning it should support types such as bytes, bytearray, and similar constructs.
Return
It produces a memoryview object based on the specified input argument.
Different Examples for Python memoryview Function
In this section, we will explore various instances of the Python memoryview function.
Python memoryview Function Example 1
The following illustration demonstrates how the memoryview function operates in Python.
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')
mv = memoryview(randomByteArray)
# access the memory view's zeroth index
print(mv[0])
# It create byte from memory view
print(bytes(mv[0:2]))
# It create list from memory view
print(list(mv[0:3]))
Output:
65
b'AB'
[65, 66, 67]
Explanation:
In the preceding illustration, we generated a memory view object named mv derived from the byte array called randomByteArray.
Next, we retrieve the element at the 0th index of the mv, which is 'A', and display it (resulting in the ASCII value of 65).
Once more, we retrieve the indices of the mv from 0 and 1 ('AB'), subsequently transforming them into byte format.
Ultimately, we retrieved all the indices from the mv and transformed it into a list. Given that bytearray internally retains the ASCII representations for the letters, the resulting output is a list containing the ASCII values corresponding to A, B, and C.
Python memoryview Function Example 2
The following illustration demonstrates the process of altering internal data through the use of the memoryview function in Python.
#random bytearray
randomByteArray = bytearray('ABC', 'utf-8')
print('Before updation:', randomByteArray)
mv = memoryview(randomByteArray)
# update 1st index of mv to Z
mv[1] = 90
print('After updation:', randomByteArray)
Output:
Before updation: bytearray(b'ABC')
After updation: bytearray(b'AZC')