memoryview () in Python

Python Methods and Functions

Therefore, before we move on to what memory scans are, we must first understand how the buffer protocol works.

Buffer protocol : The buffer protocol provides a way to access internal object data. This internal data is a memory array or buffer. This allows one object to provide its internal data (buffers), while the other — access to these buffers without intermediate copying. 
The buffer protocol is only available to us at the C-API level and does not use our usual codebase. 
Thus, memory representations are present to provide the same protocol to the normal Python codebase.

memory representation: memory representations objects allow Python code access the internal data of an object that supports the buffer protocol without copying. 
The memoryview () function provides direct read and write access to the object's byte-oriented data without having to copy it first. This can lead to significant performance gains when working with large objects because it does not create a copy when slicing.

Syntax :

  memoryview (obj)   Parameters:  obj - object whose internal data is to be exposed. supporting buffer protocol - str and bytearray (but not unicode).  Return Value:  Returns a memoryview object. 

# Python program for illustration
# Modifying internal data using memory representation

# random bytearray

byte_array = bytearray ( 'XYZ' , ' utf-8' )

print ( 'Before update:' , byte_array)


mem_view = memoryview (byte_array) < / code>

# update the second mem_view index to J

mem_view [ 2 ] = 74

print ( 'After update:' , byte_array)


 Before update: bytearray (b'XYZ') After update: bytearray (b 'XYJ') 

Explanation of how we modify the internal data in the above program: Here we have updated the 2nd index of the memory representation to an ASCII value of 74 (J). In this memory view, the mem_view object references the same buffer or memory and updates the index in mem_view and also updates the byte_array.

Importance of buffer protocol and view memory

Using the buffer protocol, we can work with big data, how we want to work with binary image data . The buffer protocol can create another accessor object to modify the big data without copying it. This forces the program to use less memory and increases the speed of execution.