buffer()Function to Implement the Buffer Interface in Python
memoryview()Function to Implement the Buffer Interface in Python
In Python, the
buffer type object is used to show the internal data of a given object in a byte-oriented format. Python’s main use of buffers is storing and manipulating huge data arrays and processing them without creating copies.
buffer interface is only supported by
numpy arrays also use this interface in the background.
We can work on the same
buffer instances without creating copies of data using the
import numpy as np arr = np.array([1,2,3]) arr2 = np.asarray(arr) arr2 = 50 print(arr, arr2)
[ 1 2 50] [ 1 2 50]
In the above example, we create a
numpy array called
arr and, using this, we create another array called
numpy module supports the buffer protocol and the data is sent using views of the array rather than generating a new array, updating the array
arr2 also updates the original
Let us implement this interface on supported objects using the
buffer() Function to Implement the Buffer Interface in Python
buffer() function, we can return a given object’s read-only view objects that support the buffer interface (
bytesarray). It is useful when working with huge data arrays because it eliminates copying the data.
a = 'Sample String' bf = buffer(a, 2, 5) print bf, type(bf)
mple <type 'buffer'>
We created a
buffer type object in the above example. This object returns a view of the string
memoryview() function replaced the
buffer() function in Python 3. Python 2.7 supports both functions.
memoryview() Function to Implement the Buffer Interface in Python
In Python 3, the
memoryview() function is used to return a
memoryview object that implements the
buffer interface and creates a view of an object that supports this interface.
memoryview() takes the bytes-like object and returns its view. On printing, it shows the memory location of the original object.
a = bytearray('Sample Bytes', 'utf-8') m = memoryview(a) print(m, type(m), m)
109 <class 'memoryview'> <memory at 0x7f83f2d5f940>
In the above example, we created a
memoryview object of an encoded