Zero Copy Slicing With memoryview
Slice a bytearray through memoryview to inspect and patch large buffers in place, avoiding full copies at every processing step.
Code
payload = bytearray(b'HEADER:payload:TAIL')
view = memoryview(payload)
print('length:', len(view), 'readonly:', view.readonly)
header = view[:6] # 视图切片不复制底层字节
print('header bytes:', bytes(header))
view[7:14] = b'CONTENT' # 通过视图就地写入
print('patched:', payload.decode())
segment = view[15:19]
segment[0:4] = b'END!'
print('tail patched:', payload.decode())
print('shares buffer:', view.obj is payload)Output
Captured from a sandboxed run of this snippet in the build pipeline.
length: 19 readonly: False
header bytes: b'HEADER'
patched: HEADER:CONTENT:TAIL
tail patched: HEADER:CONTENT:END!
shares buffer: TrueHow the snippet works
Top-level bindings payload, view, header, segment hold the demo state — nothing sits inside a function scope.
Applying it
The run emits 5 labeled sections — length:, header bytes:, patched:, tail patched:, shares buffer: — one per step.
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `payload`, `view`, `header`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.