bpo-33176 Add readonly mode to memoryviews by pablogsal · Pull Request #6314 · python/cpython
As I mentioned in my review above, there is a fundamental limitation that this PR is hitting, and it's that currently memoryview.cast() doesn't support same-shape casting for non-1D buffers. You would typically notice that if you have a view over a Numpy array.
To witness it without Numpy installed, CPython has a private type _testbuffer.ndarray that emulates a N-dimensional array. Below you can see the issue I'm talking about:
>>> a = _testbuffer.ndarray([1,2,3,4], format='B', shape=(2, 2))
>>> memoryview(a).tolist()
[[1, 2], [3, 4]]
>>> memoryview(a).cast('B').tolist()
[1, 2, 3, 4]
>>> memoryview(a).cast('B', shape=a.shape).tolist()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: memoryview: cast must be 1D -> ND or ND -> 1D
And the issue is similar if using non-byte formats and trying to cast to an identical format:
>>> a = _testbuffer.ndarray([1,2,3,4], format='i', shape=(2, 2))
>>> memoryview(a).cast('i').tolist()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: memoryview: cannot cast between two non-byte formats
For this PR to be truly useful, m.cast(m.format, m.shape, readonly=True) should be supported for any buffer kind. @skrah may have ideas on how to make it work.