How to Use MemoryView in Python The Python memoryview() function provides a zero-copy, efficient way to access and slice an object’s internal buffer data without duplicating it in memory. This tool is essential for high-performance computing, large file manipulation, and network stream processing.
Standard operations like slicing a standard string or list generate a copy of the data, which wastes RAM and processor cycles. A memoryview functions like a pointer window, giving direct access to the original underlying data structure. 🛠️ Prerequisites: The Buffer Protocol
A memoryview cannot be used on every Python object. The targeted object must support the buffer protocol. This protocol is a low-level C-API feature that exposes raw memory addresses to Python.
Supported objects: bytes, bytearray, array.array, and numpy arrays.
Unsupported objects: Standard lists, dictionaries, strings, and integers. 🚀 Step 1: Creating a Basic MemoryView
You can instantiate a memory view by wrapping an object that supports the buffer protocol inside the memoryview() constructor.
# Create a mutable bytearray data = bytearray(b”Python Execution Engine”) # Create the memoryview view = memoryview(data) # Access elements (returns ASCII integer codes) print(view[0]) # Output: 80 (ASCII code for ‘P’) print(view[1]) # Output: 121 (ASCII code for ‘y’) Use code with caution. ✂️ Step 2: Zero-Copy Slicing
Slicing a memoryview creates a new sub-view rather than a copied dataset.
# Slice the memoryview sub_view = view[7:16] # Convert the slice back to bytes to read it print(sub_view.tobytes()) # Output: b’Execution’ Use code with caution.
No new allocations occurred during the creation of sub_view. It points straight to indices 7 through 16 of the original data bytearray. ✏️ Step 3: Modifying Underlying Data
Leave a Reply