capypad
0 day streak
python / expert
Snippet

Zero-Copy Slicing with memoryview

The memoryview object allows Python code to access the internal data of an object that supports the buffer protocol (like bytearray) without copying. Slicing a memoryview returns a new memoryview that shares the same underlying buffer, enabling extremely efficient memory manipulation for large datasets.

snippet.py
python
1
2
3
4
5
6
data = bytearray(b'X' * 100_000_000)
mv = memoryview(data)
chunk = mv[1000:2000]
# No data is copied here
chunk[0] = ord('Y')
print(data[1000]) # Outputs: 89 ('Y')
Breakdown
1
mv = memoryview(data)
Creates a view of the underlying memory buffer of the bytearray.
2
chunk = mv[1000:2000]
Creates a slice of the view; this is a 'view of a view' with zero copying.
3
chunk[0] = ord('Y')
Modifying the slice directly updates the original bytearray data.