memoryview() in Python (original) (raw)

Last Updated : 22 Feb, 2025

The memoryview() function in Python is used to create a memory view object that allows us to access and manipulate the internal data of an object without copying it. This is particularly useful for handling large datasets efficiently because it avoids the overhead of copying data. A memory view object exposes the buffer interface of the underlying object, such as bytes, bytearray or array, enabling direct access to the memory.

**Example:

Python `

Creating a memory view of a bytearray

data = bytearray("Hello", "utf-8")
mv = memoryview(data)

print(mv[0])
mv[1] = 105
print(data)

`

Output

72 bytearray(b'Hillo')

**Explanation:

Table of Content

**Syntax of memoryview()

memoryview(object)

Different methods of using memoryview()

1. Accessing bytes using indexing

Memory views can be accessed using indexing and slicing, similar to sequences like lists or strings. Indexing returns the byte value at the specified position as an integer, while slicing returns a new memory view representing the specified range of bytes. This approach is particularly useful for reading specific sections of large datasets without copying the entire data into memory, which improves efficiency.

Python `

Creating a memory view from bytes

data = b'Python'
mv = memoryview(data)

Accessing individual byte using indexing

print(mv[0])

Accessing a range of bytes using slicing

print(mv[1:4].tobytes())

`

**Explanation:

2. Modifying data using bytearray

When using a mutable object like bytearray, memoryview() allows direct modification of the underlying data. Indexing can be used to update specific bytes by assigning new values (as integers representing ASCII codes). Any modifications made through the memory view immediately affect the original object. This capability is valuable for performance-critical applications where data needs to be modified without creating copies, such as image manipulation or real-time data processing.

**Example:

Python `

Creating a bytearray for mutable data

arr = bytearray(b'abcde')
mv = memoryview(arr)

Modifying a byte using indexing

mv[0] = 65
print(arr)

`

Output

bytearray(b'Abcde')

**Explanation:

3. Converting memory view to bytes

The .tobytes() method converts the memory view into an immutable bytes object, which is a copy of the original data. This is useful when you need to create a read-only snapshot of the data that won’t be affected by future changes to the original buffer. The resulting bytes object can be safely shared between functions or stored for later use, ensuring data integrity. This method is commonly used in networking, data serialization, and cryptography.

**Example:

Python `

Creating a mutable bytearray

arr = bytearray(b'12345')
mv=memoryview(arr)

Converting the memory view to immutable bytes

result = mv.tobytes()
print(result)
print(type(result))

`

Output

b'12345' <class 'bytes'>

**Explanation:

4. Using .cast() Method to Change Data Interpretation

The .cast() method allows you to reinterpret the underlying memory as a different data type without altering the actual data. This method is particularly useful for working with binary data or structured data formats, where the same bytes can represent different types depending on their interpretation. By specifying a format code (like ‘B’ for unsigned bytes or ‘i’ for integers), you can access the memory as a sequence of different-sized elements, which is essential for tasks like parsing binary files, network protocols, and image processing.

Python `

import array

Creating an array of integers

arr = array.array('i', [1, 2, 3, 4])
mv=memoryview(arr)

Reinterpreting the data as unsigned bytes

mv_cast = mv.cast('B')
print(mv_cast.tolist())

`

Output

[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0]

**Explanation: