Bytearray stores mutable bytes, while bytes stores an immutable byte sequence.
Python bytearray: mutable bytes share storage only through explicit views
Operation contract
The receipt frame begins as a bytearray. A bytes conversion makes an independent immutable snapshot. A memoryview, by contrast, observes later edits to the original buffer. The fixture changes one byte and prints all three representations, then releases its view. This distinction matters when a parser retains a buffer while a network reader refills it.
Failure and ownership boundary
A view can also prevent resizing the underlying bytearray until released. An immutable bytes snapshot costs a full copy, but avoids an alias changing between validation and use. Python memoryview: shared buffers and explicit release, Python struct: a fixed-endian receipt record with exact byte length and Python strings and bytes: reject decoding errors before parsing records separate byte ownership from decoded text.
Working program
frame = bytearray(b"R41:125")
snapshot = bytes(frame)
view = memoryview(frame)
frame[0] = ord("X")
print("snapshot:", snapshot)
print("buffer:", bytes(frame))
print("view:", view[0])
try:
frame.extend(b"!")
except BufferError:
print("resize blocked by view")
view.release()
frame.extend(b"!")
print("resized:", bytes(frame))Output
snapshot: b'R41:125'
buffer: b'X41:125'
view: 88
resize blocked by view
resized: b'X41:125!'Costs and limits
Copying n bytes to bytes takes O(n) time and storage; constructing a view retains a reference without copying the payload. A released view must not be reused, and a reader still needs a bound on retained buffers.
Common Mistakes
- A memoryview is not a frozen snapshot.
- Release a view before resizing the exporting bytearray.
Connected lessons
Python memoryview: shared buffers and explicit release, Python struct: a fixed-endian receipt record with exact byte length, Python strings and bytes: reject decoding errors before parsing records.
