Is there a pure Python way of transposing a memoryview
?
Python memoryview
s can represent more than just a 1-dimensional chunk of bytes. They can represent multidimensional layouts, noncontiguous memory, complex element types, and more. For example, in the following code:
In [1]: import numpy
In [2]: x = numpy.array([[1, 2], [3, 4]])
In [3]: y = x.T
In [4]: a = memoryview(x)
In [5]: b = memoryview(y)
a
and b
are 2-by-2 multidimensional memoryviews:
In [6]: a.shape
Out[6]: (2, 2)
In [7]: b.shape
Out[7]: (2, 2)
and b
represents a transpose of a
, so a[i, j]
and b[j, i]
alias the same memory (which is cell i, j of the original x
array):
In [8]: a[0, 1] = 5
In [9]: b[1, 0]
Out[9]: 5
In [10]: x
Out[10]:
array([[1, 5],
[3, 4]])
NumPy arrays support easy transposes, but NumPy arrays aren't the only sources of multidimensional memoryviews. For example, you can cast a single-dimensional memoryview:
In [11]: bytearr = bytearray([1, 2, 3, 4])
In [12]: mem = memoryview(bytearr).cast('b', (2, 2))
In [13]: mem.shape
Out[13]: (2, 2)
In [14]: mem[1, 0] = 5
In [15]: bytearr
Out[15]: bytearray(b'\x01\x02\x05\x04')
The memoryview format is flexible enough to represent a transpose of mem
, like what b
was to a
in our earlier example, but there doesn't seem to be an easy transpose method in the memoryview API. Is there a pure-Python way of transposing arbitrary multidimensional memoryviews?