Python memoryview() Method

The memoryview() method returns a memory view object of the given object. The memoryview object allows Python code to access the internal data of an object that supports the buffer protocol without copying.

Syntax:

memoryview(obj)

Parameters:

obj: Object whose internal data is to be exposed.

Return type:

Returns a memory view object.

The following example demonstrates the memoryview() method.

Example: memoryview()
barr = bytearray('Python','utf-8')
mv = memoryview(barr)
print(type(mv))
print(mv[0])
print(mv[1])
print(mv[2])
print(mv[3])
print(mv[4])
print(mv[5])
print('Converted to list: ', list(mv)) # convert to list
Output
<class 'memoryview'>
80
121
116
104
111
110
Converted to list: [80, 121, 116, 104, 111, 110]

We can also update the object in memory view.

Example: memoryview()
barr = bytearray('Python','utf-8')
mv = memoryview(barr)
print(type(mv))
mv[0] = 65
print(barr)
Output
bytearray(b'Aython')

Visit MemoryView for more information.

Want to check how much you know Python?