Tutorial Study Image

Python memoryview()

The built-in function memoryview() is used to return the memory view object of the given object. A memory view is a better way to expose the buffer protocol in Python. By creating a memory view object, it allows you to access the internal buffers of an object.The buffer protocol helps to access the internal data of an object, internal data may be a memory array or a buffer.


memoryview(obj) # Where obj can be a byte or bytearray
 

memoryview() Parameters:

Takes only one parameter.Here  the obj will support the buffer protocol (bytes, bytearray).

Parameter Description Required / Optional
obj  an object whose internal data is to be exposed Required

memoryview() Return Value

We can also update the object in memory view.

Input Return Value
 obj memory view object

Examples of memoryview() method in Python

Example 1: How memoryview() works in Python?


#random bytearray
random_byte_array = bytearray('ABC', 'utf-8')

mv = memoryview(random_byte_array)

# access memory view's zeroth index
print(mv[0])

# create byte from memory view
print(bytes(mv[0:2]))

# create list from memory view
print(list(mv[0:3]))
 

Output:

65
b'AB'
[65, 66, 67]

Example 2: Modify internal data using memory view


# random bytearray
random_byte_array = bytearray('ABC', 'utf-8')
print('Before updation:', random_byte_array)

mv = memoryview(random_byte_array)

# update 1st index of mv to Z
mv[1] = 90
print('After updation:', random_byte_array)
 

Output:

Before updation: bytearray(b'ABC')
After updation: bytearray(b'AZC')

Example 3: Update the object in memory view.


barr = bytearray('Python','utf-8')
mv = memoryview(barr)
print(type(mv))
mv[0] = 65
print(barr)
 

Output:

bytearray(b'Aython')