InterviewSolution
| 1. |
What is memoryview object in Python? |
|
Answer» A memory view OBJECT is returned by memoryview() a built-in function in standard library. This object is SIMILAR to a sequence but allows access to the internal data of an object that supports the buffer protocol without copying. Just as in the C language, we access the memory using pointer variables; in PYTHON; we use memoryview to access its referencing memory. Buffer Protocol allows exporting an interface to access internal memory (or buffer). The built-in TYPES bytes and bytearray supports this protocol and objects of these classes are allowed to expose internal buffer to allow to directly access the data. Memory view objects are required to access the memory directly instead of data duplication. The memoryview() function has one object that supports the buffer protocol as argument. >>> obj=memoryview(b'HELLO Python') >>> obj <memory at 0x7ffa12e2b048>This code creates a memoryview of bytesarray >>> obj1=memoryview(bytearray("Hello Python",'utf-8')) >>> obj1 <memory at 0x7ffa12e2b108>A memoryview supports slicing and indexing to expose its data. >>> obj[7] 121Slicing creates a subview >>> v=obj[6:] >>> bytes(v) b'Python' |
|