Python memoryview() function

Published February 16, 2022

Python's memoryview() method is used to return memory view objects. In Python, a memory view exposes the buffer protocol in a safe way. By using Memoryview objects, objects can access the internal data of objects that support the buffer protocol without copying data. By using the memoryview() function, you have direct access to byte-oriented data of an object without having to copy it first.
Because it does not need copying while slicing, this approach enhances speed, particularly when dealing with huge objects.

Syntax
Let's have a look at the memoryview() function's syntax:

memoryview(object whose internal data will be revealed)


Example
Let's have a look at the sample below to see how the memeoryview() method works.

x = bytearray('XYZ', 'utf-8')
a = memoryview(x)
print(a[0])
print(bytes(a[0:1]))

Output
If you run this code, the following will be output:

88
b'X'

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

333 Views