Python memoryview() Built in Function

The memoryview() function in Python returns a memory view object of a given argument. A memory view object allows you to access the internal data of an object that supports the buffer protocol without copying it. The buffer protocol provides a way to access the low-level memory of an object. Examples of objects that support the buffer protocol are bytes, bytearray, array.array, etc.

Here are some examples of using memoryview() function in Python:

Using memoryview() with a bytearray

# This example creates a memory view object from a bytearray and prints its elements
byte_array = bytearray('ABC', 'utf-8')
mv = memoryview(byte_array)
print(mv[0])
# Output: 65
print(bytes(mv[0:2])) # Output: b'AB'
print(list(mv[0:3])) # Output: [65 ,66 ,67]

Using memoryview() to modify internal data

# This example modifies the first element of a bytearray using a memory view object
byte_array = bytearray('ABC', 'utf-8')
print('Before update:', byte_array)
# Output: bytearray(b'ABC')
mem_view = memoryview(byte_array)
mem_view[0] = 88
# ASCII value of 'X'
print('After update:', byte_array) # Output: bytearray(b'XBC')

Using memoryview() with an array

# This example creates a memory view object from an array and prints its elements
import array
arr = array.array('i', [1, 2, 3])
mv = memoryview(arr)
print(mv[0])
# Output: 1
print(bytes(mv[0:2])) # Output: b'\x01\x00\x00\x00\x02\x00\x00\x00'
print(list(mv[0:3])) # Output: [1 ,2 ,3]

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions