python buffer

Python provides such a facility at the C level in the form of the buffer protocol. This protocol has two sides:

    on the producer side, a type can export a “buffer interface” which allows objects of that type to expose information about their underlying buffer. This interface is described in the section Buffer Object Structures;

    on the consumer side, several means are available to obtain a pointer to the raw underlying data of an object (for example a method parameter).

Simple objects such as bytes and bytearray expose their underlying buffer in byte-oriented form. Other forms are possible; for example, the elements exposed by an array.array can be multi-byte values.

An example consumer of the buffer interface is the write() method of file objects: any object that can export a series of bytes through the buffer interface can be written to a file. While write() only needs read-only access to the internal contents of the object passed to it, other methods such as readinto() need write access to the contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write and read-only buffers.

There are two ways for a consumer of the buffer interface to acquire a buffer over a target object:

    call PyObject_GetBuffer() with the right parameters;

    call PyArg_ParseTuple() (or one of its siblings) with one of the y*, w* or s* format codes.

In both cases, PyBuffer_Release() must be called when the buffer isn’t needed anymore. Failure to do so could lead to various issues such as resource leaks.

Here is what the above code is Doing:
1. Create a bytearray object with the contents of the string “Hello, world!”
2. Get a read-only buffer view over the bytearray
3. Write the buffer contents to a file
4. Release the buffer

The buffer protocol is also used by the memoryview type.