Python memoryview()
Function
The memoryview() function in Python provides a way to access the memory of a binary object (like bytes
or bytearray
) without copying the actual data. It's very useful for working with large data buffers efficiently.
Syntax
memoryview(obj)
Parameters:
obj
– A binary object that supports the buffer protocol, likebytes
,bytearray
, orarray.array
.
Returns:
- A memoryview object that references the same data without copying it.
Example: Using memoryview()
with bytearray
data = bytearray("hello", "utf-8")
mv = memoryview(data)
print(mv[0]) # Output: 104 (ASCII of 'h')
mv[0] = 72 # Change 'h' to 'H'
print(data) # Output: bytearray(b'Hello')
104
bytearray(b'Hello')
Why Use memoryview()
?
- Efficient: No need to copy data
- Fast: Great for performance with large datasets
- Direct access: You can slice, read, or modify without unpacking
Example: Slicing Memory Efficiently
numbers = bytearray([10, 20, 30, 40, 50])
mv = memoryview(numbers)
slice_mv = mv[1:4]
print(list(slice_mv))
[20, 30, 40]
Converting Back to Bytes
mv = memoryview(b"data")
print(bytes(mv))
b'data'
Common Mistakes
- Using
memoryview()
on non-buffer objects like strings → will raiseTypeError
- Trying to assign new values to a
memoryview
ofbytes
(which is immutable)
Interview Tip
In performance-sensitive applications (like image processing, network packets, or binary file handling), memoryview()
helps reduce memory overhead.
Summary
memoryview()
gives you access to the internal data of a binary object.- It is efficient because it avoids data copying.
- Supports slicing and modification (if the source is mutable).
Practice Problem
Create a bytearray
from the word "data"
, convert it to a memoryview, change 'd' to 'D', and print the updated bytearray.
b = bytearray("data", "utf-8")
mv = memoryview(b)
mv[0] = ord("D")
print(b)
Expected Output:
bytearray(b'Data')