Respect Buffer Ownership and Lifetime
Core idea
The buffer protocol exposes memory through an exporter and consumer. A memoryview may share storage without copying; its metadata describes shape, format, strides and read-only status. Native consumers use PyObject_GetBuffer and release a successfully acquired Py_buffer with PyBuffer_Release. A view can prevent resizing an exporter while active.
data=bytearray(b'abc')with memoryview(data) as view: view[0]=ord('X') print(view.nbytes,view.readonly)print(bytes(data))The view writes through to the exporter; its context releases the view.
Expected output:
3 Falseb'Xbc'Release before resizing
data=bytearray(b'a')with memoryview(data): try: data.extend(b'b') except BufferError: print('export active')data.extend(b'b')print(bytes(data))The live export blocks resizing; after release the bytearray can grow.
Expected output:
export activeb'ab'Common mistake
Read-only does not necessarily mean immutable backing storage. Never assume contiguity or use a native pointer after release.
Practice
Compare a sliced view with a copied bytes value. Inspect contiguous and readonly, and release all views before resizing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Buffer interoperability
Check your understanding of buffer interoperability.
What is printed?
with memoryview(b"ab") as m: print(m.readonly)What is printed?
with memoryview(bytearray(b"abc")) as m: print(m.nbytes)What must follow successful PyObject_GetBuffer?
Does a read-only view guarantee immutable backing data?