Skip to content

Commit dec1842

Browse files
committed
✨ HasTranspose
Signed-off-by: nstarman <nstarman@users.noreply.github.com>
1 parent 56708a1 commit dec1842

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

src/array_api_typing/_array.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,36 @@ def size(self) -> int | None:
151151
...
152152

153153

154+
class HasTranspose(Protocol):
155+
"""Protocol for array classes that support the transpose operation."""
156+
157+
@property
158+
def T(self) -> Self: # noqa: N802
159+
"""Transpose of the array.
160+
161+
The array instance must be two-dimensional. If the array instance is not
162+
two-dimensional, an error should be raised.
163+
164+
Returns:
165+
Self: two-dimensional array whose first and last dimensions (axes)
166+
are permuted in reverse order relative to original array. The
167+
returned array must have the same data type as the original
168+
array.
169+
170+
Notes:
171+
Limiting the transpose to two-dimensional arrays (matrices) deviates
172+
from the NumPy et al practice of reversing all axes for arrays
173+
having more than two-dimensions. This is intentional, as reversing
174+
all axes was found to be problematic (e.g., conflicting with the
175+
mathematical definition of a transpose which is limited to matrices;
176+
not operating on batches of matrices; et cetera). In order to
177+
reverse all axes, one is recommended to use the functional
178+
`PermuteDims` interface found in this specification.
179+
180+
"""
181+
...
182+
183+
154184
class Array(
155185
# ------ Attributes -------
156186
HasDType[DTypeT_co],
@@ -159,6 +189,7 @@ class Array(
159189
HasNDim,
160190
HasShape,
161191
HasSize,
192+
HasTranspose,
162193
# ------- Methods ---------
163194
HasArrayNamespace[NamespaceT_co],
164195
# -------------------------

tests/integration/test_numpy1p0.pyi

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,7 @@ _: tuple[int | None, ...] = x_i32.shape
7575
# Check Attribute `.size`
7676
_: int | None = x_f32.size
7777
_: int | None = x_i32.size
78+
79+
# Check Attribute `.T`
80+
_: xpt.Array[dtype[Any]] = x_f32.T
81+
_: xpt.Array[dtype[Any]] = x_i32.T

tests/integration/test_numpy2p0.pyi

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,8 @@ _: tuple[int | None, ...] = x_b.shape
8686
_: int | None = x_f32.size
8787
_: int | None = x_i32.size
8888
_: int | None = x_b.size
89+
90+
# Check Attribute `.T`
91+
_: xpt.Array[np.dtype[F32]] = x_f32.T
92+
_: xpt.Array[np.dtype[I32]] = x_i32.T
93+
_: xpt.Array[np.dtype[B]] = x_b.T

0 commit comments

Comments
 (0)