How to Use Python’s memoryview with Examples

This video introduces the `memoryview` data type in Python, which allows direct access to an object’s internal data supporting the buffer protocol without copying. It demonstrates practical examples of using `memoryview` for efficient data manipulation, covering basic usage, slicing, and handling multi-dimensional arrays.

1. Video.

2. Python Source Code.

def basic_usage():
    # Create a byte array
    data = bytearray(b'Python!')
    
    # Create a memoryview object
    view = memoryview(data)
    print(view)
    
    # Print the original data
    print("Original data:", view.tobytes())
    
    # Modify the data
    view[0] = ord('p')
    
    # Print the modified data
    print("Modified data:", view.tobytes())

## Example 2: Slicing
def slicing():
    # Create a byte array
    data = bytearray(b'Python!')
    
    # Create a memoryview object
    view = memoryview(data)
    
    # Slice the memoryview object
    sliced_view = view[2:6]
    
    # Print the sliced view
    print("Sliced view:", sliced_view.tobytes())
    
    # Modify the sliced view
    sliced_view[0] = ord('T')
    
    # Print the modified sliced view
    print("Modified sliced view:", sliced_view.tobytes())
    
    # Print the modified original data
    print("Modified original data:", view.tobytes())

## Example 3: Multi-dimensional Array
def multi_dimensional():
    import numpy as np
    
    # Create a multi-dimensional array
    data = np.arange(6, dtype='int16').reshape(2, 3)
    
    # Create a memoryview object
    view = memoryview(data)
    
    # Print the original data
    print("Original data:\n", view.tolist())
    
    # Modify the data
    view[1, 1] = 99
    
    # Print the modified data
    print("Modified data:\n", view.tolist())

## Main Function
def main():
    # Call basic usage example
    basic_usage()
    
    # Call slicing example
    #slicing()
    
    # Call multi-dimensional array example
    #multi_dimensional()

if __name__ == "__main__":
    main()

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.