BufferError
A memoryview points straight at an object's memory, so while one exists the object may change its bytes but not its length.
Demo
buf = bytearray(b'abc') view = memoryview(buf) buf[0:1] = 'X'.encode() bytes(buf)
'X' works because it is exactly one byte and the length stays 3. 'é' looks like one character but .encode() makes it two bytes, so it is a resize and fails like 'XYZ' and ''. In Handle, the view is already released when the assignment runs, and every input succeeds.
Constructor
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | The message. Built-in types pass one string describing what could not be done. |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | The message tuple, e.g. ('Existing exports of data: object cannot be re-sized',). |
Common patterns
with memoryview(buf) as view: header = bytes(view[:4]) buf.extend(more)
view = memoryview(buf) process(view) view.release() buf.clear()
stream = io.BytesIO() with stream.getbuffer() as view: checksum = zlib.crc32(view) stream.write(b'more')
Examples
Pitfalls
buf = bytearray(b'hdr') view = memoryview(buf) header = bytes(view[:3]) buf.extend(b'body')
buf = bytearray(b'hdr') with memoryview(buf) as view: header = bytes(view[:3]) buf.extend(b'body') buf
import io stream = io.BytesIO(b'data') view = stream.getbuffer() stream.close()
import io stream = io.BytesIO(b'data') view = stream.getbuffer() size = len(view) view.release() stream.close() size
When to use
- Raising it from your own C extension or buffer-exporting type when a buffer request cannot be met
- Recognising "a memoryview is still alive somewhere" in a traceback
- Holding memoryviews longer than needed
- Assuming del view always frees the export — another name, a slice, or a traceback frame may still hold it; release() is explicit
Notes
FAQ
Some memoryview (or a slice of one, or a BytesIO.getbuffer() result) still refers to the object you are resizing. Call view.release() before the append/extend/write/close, or create the view in a with memoryview(obj) as view: block so it is released automatically. In-place changes that keep the length — view[0] = 1 or buf[0:1] = b"X" — are allowed while the view exists.