memoryview.cast()
Reinterpret a C-contiguous buffer as another native single-element format, optionally changing its dimensions. The new view shares storage with the original, preserving total byte length; it does not numerically convert elements or change byte order. One of the source or destination formats must be a byte format (B, b or c). Casts support a one-dimensional source to a C-contiguous layout, or a C-contiguous source to one dimension; use an intermediate one-dimensional byte view to reshape other layouts. Omit shape for a one-dimensional result. Native sizes and endianness depend on the platform. Noncontiguous input, incompatible lengths, or invalid formats fail. CPython 3.13.5 also accepts format and shape by keyword.
Formal Syntax & Structure
view.cast(format)view.cast(format, shape)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| format | str | Native single-element destination format. |
| shape | list[int] | tuple[int, ...] | Optional dimensions whose product matches the new element count. |
Return Value
New view over shared storage.
Working Example
data = bytearray(b"ABCDEF")view = memoryview(data).cast("B", shape=[2, 3])print(view.shape, view.strides)view[1, 1] = 90print(data)print(view.tolist())