Skip to content

gh-78959: Add order parameter to memoryview.cast() - #153663

Merged
serhiy-storchaka merged 2 commits into
python:mainfrom
serhiy-storchaka:memoryview-cast-order
Aug 3, 2026
Merged

gh-78959: Add order parameter to memoryview.cast()#153663
serhiy-storchaka merged 2 commits into
python:mainfrom
serhiy-storchaka:memoryview-cast-order

Conversation

@serhiy-storchaka

Copy link
Copy Markdown
Member

memoryview.cast() now accepts a keyword-only order parameter. With a multidimensional shape, order='F' returns a zero-copy Fortran-contiguous (column-major) view of a flat buffer, while order='C' (the default) keeps the current C-contiguous behavior. This mirrors the order argument of memoryview.tobytes() and makes it possible to interface with column-major libraries from pure Python without copying.

>>> buf = bytes(range(6))
>>> y = memoryview(buf).cast('B', shape=[3, 2], order='F')
>>> y.f_contiguous
True
>>> y.tolist()
[[0, 3], [1, 4], [2, 5]]

Only 'C' and 'F' are accepted; anything else raises ValueError, and non-single-character values raise TypeError. Unlike memoryview.tobytes(), None is not accepted, since the default already means 'C'.

memoryview.cast() now accepts a keyword-only order parameter.  With
order='F' it returns a zero-copy Fortran-contiguous (column-major) view
of a flat buffer, mirroring the order argument of memoryview.tobytes().
Only 'C' (the default) and 'F' are accepted; the buffer is not copied.
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #33564450 | 📁 Comparing b58343f against main (1fece44)

  🔍 Preview build  

3 files changed
± library/stdtypes.html
± whatsnew/3.16.html
± whatsnew/changelog.html

@serhiy-storchaka
serhiy-storchaka merged commit bd8b2fe into python:main Aug 3, 2026
52 of 53 checks passed
@serhiy-storchaka
serhiy-storchaka deleted the memoryview-cast-order branch August 3, 2026 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant