The method .getbuffer()
is commonly used in Python with io.BytesIO
or io.StringIO
objects.
.getbuffer()
returns a memoryview object of the underlying buffer (the raw data) without making a copy.
This means you can access, read, or manipulate the buffer contents directly in memory—very efficient!
Works only on binary streams like io.BytesIO
, not StringIO
.
No data copy → faster and memory-efficient compared to .getvalue()
.
You can slice, read, or modify data directly.
import io
# Create a BytesIO stream
stream = io.BytesIO(b"Hello World")
# Get buffer (memoryview)
buffer = stream.getbuffer()
print(buffer) # <memory at 0x...>
print(buffer.tobytes()) # b'Hello World'
print(buffer[0:5]) # b'Hello'
# Modify buffer directly
buffer[0:5] = b"Hi!!!"
print(stream.getvalue()) # b'Hi!!! World'
.getvalue()
vs .getbuffer()
Method | Returns | Copies Data? | Editable? |
---|---|---|---|
.getvalue() |
bytes object |
✅ Yes | ❌ No |
.getbuffer() |
memoryview |
❌ No | ✅ Yes |
👉 So, .getbuffer()
is mainly used when you need zero-copy access to a BytesIO
buffer.