memoryview() provides direct access to an object’s memory (like bytes, bytearray, or array) without copying it, making operations on large datasets faster and more efficient.
Example:
# 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:
- bytearray("Hello", "utf-8"): stores the string as bytes you can change.
- memoryview(data): lets you look at and change the data directly without making a copy.
- mv[0]: prints the ASCII code of 'H' (72).
- mv[1] = 105: changes 'e' to 'i', so the array becomes b'Hillo'.
Syntax
memoryview(object)
- object: A buffer-supporting object (bytes, bytearray, array, etc.)
- Returns: A memory view object that can access the underlying memory directly.
Different methods of Using memoryview()
1. Accessing bytes using indexing
You can use indexing or slicing to access specific bytes in a memory view.
data = b'Python'
mv = memoryview(data)
print(mv[0])
print(mv[1:4].tobytes())
Output
80 b'yth'
Explanation:
- mv[0]: returns the ASCII value of 'P'.
- mv[1:4]: slices the memory view; .tobytes() converts it to a bytes object (b'yth').
- Memory view allows access without copying the original d
2. Modifying data using bytearray
If the underlying object is mutable (like bytearray), you can modify it directly through the memory view.
arr = bytearray(b'abcde')
mv = memoryview(arr)
# Modifying a byte using indexing
mv[0] = 65
print(arr)
Output
bytearray(b'Abcde')
Explanation:
- memoryview(arr): creates a view of the bytearray without copying.
- Modifying mv[0] directly changes the original bytearray.
- Saves memory by avoiding data copies.
3. Converting memory view to bytes
The .tobytes() method converts the memory view into an immutable bytes object, which is a copy of the data.
Example:
arr = bytearray(b'12345')
mv=memoryview(arr)
res = mv.tobytes()
print(res)
print(type(res))
Output
b'12345' <class 'bytes'>
Explanation:
- memoryview(arr): creates a view of the bytearray without copying.
- .tobytes(): produces an immutable copy of the data as a bytes object.
- Changes to mv or arr after this do not affect res.
4. Reinterpreting Data Using .cast()
The .cast() method lets you interpret the memory as a different data type without changing the actual data. This is useful when working with binary data or arrays.
import array
arr = array.array('i', [1, 2, 3, 4])
mv=memoryview(arr)
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:
- array.array('i', [1,2,3,4]): array of integers (4 bytes each).
- memoryview(arr): view of the array without copying.
- mv.cast('B'): reinterpret each integer as 4 unsigned bytes.
- .tolist(): convert memory view to a list of bytes.