BytesIO getbuffer Exposes Zero-Copy Writable Views
Mutate an in-memory BytesIO stream through getbuffer() without copying bytes, and release the memoryview cleanly before resizing or closing.
Code
import io
stream = io.BytesIO(b"PKT-0000-READY")
# getbuffer() exports a writable memoryview directly over the internal buffer
with stream.getbuffer() as view:
view[4:8] = b"0042"
try:
# Resizing writes fail with BufferError while an exported view is still alive
stream.write(b"-TAIL")
except BufferError as exc:
print("locked while view open:", exc)
# Once the memoryview context exits, resizing writes work again
stream.seek(0, io.SEEK_END)
stream.write(b"-OK")
print("final bytes:", stream.getvalue().decode("ascii"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
locked while view open: Existing exports of data: object cannot be re-sized
final bytes: PKT-0042-READY-OKAnnotated execution — BytesIO getbuffer Exposes Zero-Copy Writable Views
The file’s state is a handful of top-level bindings: stream.
Caveats
- Zero packages pulled in — the runtime ships every API this code touches.
Applying it
The demo output is labeled (locked while view open:, final bytes:); each label names the call that printed it.
Statements that matter
with stream.getbuffer() as view:
view[4:8] = b"0042"
try:
# Resizing writes fail with BufferError while an exported view is still alive
stream.write(b"-TAIL")
except BufferError as exc:
print("locked while view open:", exc)
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `io`. Its state lives in module-level bindings: `stream`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.