Objects/memoryobject.c (part 5)
Source:
cpython 3.14 @ ab2d84fe1023/Objects/memoryobject.c
This annotation covers slicing, reinterpretation, and conversion. See objects_memoryobject4_detail for memoryview.__new__, PyBUF_* flags, and the buffer protocol.
Map
| Lines | Symbol | Role |
|---|---|---|
| 1-80 | memoryview.__getitem__ | Element access and slicing |
| 81-180 | memoryview.cast | Reinterpret format/shape |
| 181-280 | memoryview.tobytes | Copy to bytes |
| 281-380 | memoryview.tolist | Convert to nested Python list |
| 381-500 | memoryview.release | Release underlying buffer |
Reading
memoryview.__getitem__
// CPython: Objects/memoryobject.c:1820 memory_subscript
static PyObject *
memory_subscript(PyMemoryViewObject *self, PyObject *key)
{
Py_buffer *view = &self->view;
if (PyIndex_Check(key)) {
Py_ssize_t index = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (view->ndim == 1) {
/* Return scalar element */
return unpack_single(self, view->buf + index * view->strides[0],
view->format);
}
/* Multi-dimensional: return sub-view */
return memory_slice(self, key);
}
if (PySlice_Check(key)) {
return memory_slice(self, key);
}
...
}
For 1-D contiguous views, mv[i] unpacks the element at byte offset i * strides[0] using the format string (e.g., 'B' for uint8, 'i' for int32). For slices, a new memoryview is returned that shares the same underlying buffer with adjusted buf, len, strides.
memoryview.cast
// CPython: Objects/memoryobject.c:1600 memory_cast
static PyObject *
memory_cast(PyMemoryViewObject *self, PyObject *args, PyObject *kwds)
{
/* cast(format[, shape]) — reinterpret the bytes */
const char *fmt;
PyObject *shape = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:cast", ...)) return NULL;
/* Validate: same total byte size */
Py_ssize_t itemsize = get_native_itemsize(fmt);
if (self->view.len % itemsize != 0) {
PyErr_SetString(PyExc_TypeError, "memoryview: length is not a multiple of itemsize");
return NULL;
}
return mbuf_copy(self->mbuf, &self->view, fmt, shape, ...);
}
mv.cast('H') reinterprets a byte buffer as 16-bit unsigned shorts. The total byte length must be divisible by the new item size. The resulting view shares the same memory — no data is copied. Used to read raw binary data in a typed way.