A memoryview exposes a supported buffer without copying its bytes; a view of mutable storage can write into that storage.
Python memoryview: shared buffers and explicit release
Operation contract
The upload header belongs to a bytearray. A sliced view selects two bytes and changing that view changes the owned header. The program releases both views before growing the bytearray. This distinction matters when a parser returns a view: the caller receives access to the original buffer, not a stable snapshot. Use bytes when a retained independent result is required.
Failure and ownership boundary
An exported view prevents size-changing operations on this bytearray. Releasing a parent view does not revoke a separately retained child view. A view can also have a format or stride that a downstream API cannot consume as contiguous bytes. Python strings and bytes: reject decoding errors before parsing records and NumPy slices and indexed copies: verify who owns the buffer have comparable ownership concerns.
Working program
header = bytearray(b"ABCD")
view = memoryview(header)
selected = view[1:3]
selected[0] = ord("Z")
print(bytes(header))
try:
header.append(0)
except BufferError:
print("resize blocked while exported")
selected.release()
view.release()
header.append(0)
print(len(header))Output
b'AZCD'
resize blocked while exported
5Costs and limits
Creating this contiguous view retains references without duplicating n buffer bytes. Converting it to bytes copies O(n) data. A tiny slice can keep a large exporter alive; avoid calling retained views free storage.
Common Mistakes
- A view is not an immutable snapshot of a mutable exporter.
- Release every retained child before resizing its bytearray.
Connected lessons
Python strings and bytes: reject decoding errors before parsing records, NumPy slices and indexed copies: verify who owns the buffer, Python shallow and deep copies: preserve aliases deliberately.
Check the next state boundary
Python array: fixed-width numeric storage is not a portable wire encoding.
Follow the service contract
Python struct: a fixed-endian receipt record with exact byte length.
Trace the related workflow
Python bytearray: mutable bytes share storage only through explicit views.
