Share Binary Data with memoryview
Core idea
A memoryview exposes a compatible buffer without copying its payload. A slice can share the underlying data. A writable view can modify a mutable exporter; a read-only view cannot write through itself.
data = bytearray(b"abcd")with memoryview(data) as view: view[1:3] = b"XY" print(bytes(data))Slice assignment changes the original buffer. The with statement releases the view at exit; context managers are covered next.
Make an independent snapshot
data = bytearray(b"ab")view = memoryview(data)snapshot = view.tobytes()data[0] = 90print(snapshot, view.tobytes())view.release()tobytes copies the current contents; the view continues to observe changes until released.
Common mistake
A read-only view of mutable data is not an immutable snapshot. Release all outstanding views before resizing a bytearray.
Practice
Create a view and a bytes snapshot of a bytearray; change one byte and compare them before releasing the view.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Shared views and copies
Check your understanding of memoryview.
What is printed?
b = bytearray(b"A")v = memoryview(b)b[0] = 90print(v[0])v.release()What is printed?
v = memoryview(b"a")print(v.readonly)v.release()Which operation creates a bytes snapshot?
What must be done before resizing an exported bytearray?