Python’s memoryview() Function

Learn Python @

Python’s memoryview() function provides a powerful way to work with memory buffers in an efficient manner. In this comprehensive guide, we’ll delve into the intricacies of memoryview(), covering its syntax, applications, and practical examples to help you leverage its capabilities in Python programming.

Understanding memoryview() Function:

The memoryview() function in Python is used to create a memory view object that exposes an array’s data in a more efficient and low-level manner. Its syntax is as follows:

  • obj: The object whose memory buffer is to be exposed.

Example 1: Basic Usage

Let’s start with a simple example:

# Create a bytes object
data = b'Hello, World!'
# Create a memory view object
mv = memoryview(data)
print(mv)  # Output: <memory at 0x7fb5e7b1dd00>

Here, we create a bytes object data containing the string “Hello, World!”. Then, we create a memory view object mv using memoryview(), which provides a view of the underlying memory buffer.

Example 2: Accessing Elements

You can access individual elements of the memory buffer using indexing:

print(mv[0])   # Output: 72
print(mv[6])   # Output: 87

Here, we access individual elements of the memory buffer by index.

Example 3: Slicing

Memory views support slicing operations:

print(mv[7:12])   # Output: b'World'

In this example, we slice the memory view object mv to retrieve the substring “World”.

Example 4: Modifying Bytes

You can also modify the underlying bytes through the memory view:

mv[13:] = b'Python!'
print(data)   # Output: b'Hello, World!Python!'

Here, we modify the memory view object mv to change “World!” to “Python!”. This modification reflects in the original bytes object data.

Example 5: Creating Memory View from List

You can create a memory view from a list:

lst = [1, 2, 3, 4, 5]
mv_lst = memoryview(lst)
print(mv_lst[0])   # Output: 1

In this example, we create a memory view object mv_lst from the list lst.

Author: user