The memoryview()
function provides a memory-efficient way to access and manipulate binary data (bytes, bytearray) without copying it. It’s useful for low-level programming, optimizing performance, and working with large datasets.
Example
data = bytearray([65, 66, 67, 68]) # ASCII for 'ABCD'
view = memoryview(data)
print(view[0])
# Output: 65 (ASCII for 'A')
This accesses the first byte without copying the data.
Syntax
memoryview(object)
- object → A
bytes
orbytearray
object. - Returns → A
memoryview
object (a direct reference to memory).
1. Modifying Data Without Copying
Memory views allow modifying a bytearray
without duplication.
data = bytearray([1, 2, 3, 4])
view = memoryview(data)
view[1] = 255 # Modify directly
print(data)
# Output: bytearray([1, 255, 3, 4])
Efficient for editing large datasets.
2. Slicing a memoryview
You can extract parts of the memory efficiently.
view_slice = view[1:3] # Slice memory view
print(list(view_slice))
# Output: [255, 3]
Unlike slicing a bytearray
, this does not create a new copy.
3. Converting Back to bytes
or list
Convert back for compatibility with other operations.
data_bytes = bytes(view)
print(data_bytes)
# Output: b'\x01\xff\x03\x04'
data_list = list(view)
print(data_list)
# Output: [1, 255, 3, 4]
Useful for retrieving data in a different format.
4. Viewing Memory as Another Type
View memory as different types (e.g., integers, characters).
view = memoryview(b"hello")
print(view.tolist())
# Output: [104, 101, 108, 108, 111] (ASCII values)
Helps when interpreting binary data.
Key Notes
- ✔ Accesses and modifies byte data without copying.
- ✔ Supports slicing for efficient memory access.
- ✔ Converts between bytes, lists, and other types.
- ✔ Optimized for performance in large datasets and low-level programming.
By using memoryview()
, you can process binary data efficiently, making it ideal for working with files, networking, and optimizing memory usage. 🚀