The Array API Standard
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page targets NumPy 2.5 (examples were run on NumPy 2.5.4 with array-api-strict 2.6.1 and array-api-compat 1.16), checked against the official documentation in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. NumPy, CuPy, PyTorch, JAX and others each have their own array class, with slightly different names and rules. The Python array API standard, maintained by the Consortium for Python Data API Standards, defines the common subset so that a library can write one function and run it on any conforming array. NumPy follows it in its main namespace; the protocols that carry the data between libraries are on Interoperability: Protocols and DLPack.
Which version does NumPy 2.5 follow?
The official page states that the NumPy main namespace, numpy.fft and numpy.linalg are compatible with version 2024.12 of the standard, and that NumPy aims to follow future versions when its backwards-compatibility policy allows. Version 2024.12 was adopted in NumPy 2.3 (the 2.3 release notes say the supported version was raised from 2023.12 to 2024.12). The history is short:
| NumPy | Array API support |
|---|---|
1.22 to 1.26 |
Experimental, separate |
2.0 |
|
2.1 |
Support for 2023.12, for example |
2.3 |
Version raised to 2024.12. |
2.4 |
The type signature of |
2.5 |
|
Older books and tutorials (before 2024) that import numpy.array_api or call it experimental describe a module that no longer exists; the standard is now served by import numpy as np itself (NEP 56, which replaced NEP 47’s separate-namespace approach).
Two inconsistencies are worth knowing about:
-
The official page for 2.5 still says the main namespace "is compatible with the 2024.12 version" and refers to "NumPy 2.3.0" in its body. Follow the release notes for what changed when.
-
On NumPy 2.5.4,
np.__array_api_version__reports'2025.12'(the newest version of the standard), whilex.__array_namespace__(api_version="2025.12")raises aValueErrorand versions up to 2024.12 are accepted. Passapi_version="2024.12"explicitly in your code, and do not read the attribute as proof of 2025.12 compliance.
Known differences from the standard
The page lists these deviations:
-
sum,prodandtrace, and the function signatures in general, follow the 2023.12 version of the standard rather than 2024.12. -
In-place operators with unsafe casts are forbidden by the standard but allowed by NumPy. This is described as the only known incompatibility that may remain.
-
A few very minor exceptions are documented in NEP 56.
The consequence for portable code is simple: write only what the standard names, and test it with a strict implementation (below) rather than assuming that code which works on NumPy is standard-compliant.
The standard names in NumPy
NumPy’s main namespace now provides the standard’s names alongside its older ones. Where the two differ, prefer the standard spelling in code that must run on other libraries.
| Standard name | Older NumPy name | Note |
|---|---|---|
|
|
Same behaviour. |
|
|
Axes are required; |
|
|
Aliases. |
|
|
Stacked, axis-aware vector operations (see Linear Algebra). |
|
|
A function, since array classes need not have the method. |
|
|
Kinds such as |
|
|
Fixed result shapes per function. |
|
|
Can include an initial zero or one. |
|
|
Canonical again in NumPy 2. |
import numpy as np
x = np.arange(6.0).reshape(2, 3)
print(np.concat([x, x], axis=0).shape, np.permute_dims(x, (1, 0)).shape, np.matrix_transpose(x).shape)
print(np.vecdot(x, x), np.linalg.vector_norm(x), np.linalg.matrix_norm(x))
print(np.astype(x, np.int8).dtype, np.isdtype(x.dtype, "real floating"))
print(np.unique_counts(np.array([3, 1, 3])))
print(np.sort(np.array([3, 1, 2]), descending=True), np.cumulative_sum(np.arange(4)))
print(np.pow(2, 3), np.acos(0.5), np.atan2(1.0, 1.0), np.bitwise_left_shift(1, 3))
Output:
(4, 3) (3, 2) (3, 2) [ 5. 50.] 7.416198487095663 7.416198487095663 int8 True UniqueCountsResult(values=array([1, 3]), counts=array([1, 2])) [3 2 1] [0 1 3 6] 8 1.0471975511965976 0.7853981633974483 8
The descending=True keyword of np.sort and np.argsort was added in NumPy 2.5 to comply with the standard; NaNs go to the end in both directions, and it is not available for void, object or generic dtypes. The 2.5 release notes also recommend np.trunc over the deprecated np.fix because it follows the standard. Both are covered in Sorting, Searching and Counting.
Discovering a namespace and its capabilities
Two special methods make library-agnostic code possible without importing a specific library.
-
x.__array_namespace__(api_version=None)returns the module that implements the standard for the arrayx. For a NumPy array it isnumpyitself. Passingapi_versionasks for a specific version and raisesValueErrorif it is not supported. -
np.__array_namespace_info__()returns an object with the standard’s inspection functions:capabilities(),default_device(),default_dtypes(),dtypes()anddevices().
NumPy also registers an entry point in the array_api group so that tools can discover it.
import numpy as np
from importlib.metadata import entry_points
print(entry_points(group="array_api", name="numpy"))
info = np.__array_namespace_info__()
print(info.default_device(), info.devices())
print(info.default_dtypes())
print(sorted(info.capabilities().items()))
print(list(info.dtypes(kind="real floating")))
x = np.arange(6.0).reshape(2, 3)
xp = x.__array_namespace__(api_version="2024.12")
print(xp is np, x.device, x.mT.shape)
try:
x.__array_namespace__(api_version="2099.01")
except ValueError as exc:
print("ValueError -", exc)
print(np.__array_api_version__)
Output:
EntryPoints((EntryPoint(name='numpy', value='numpy', group='array_api'),))
cpu ('cpu',)
{'real floating': dtype('float64'), 'complex floating': dtype('complex128'), 'integral': dtype('int64'), 'indexing': dtype('int64')}
[('boolean indexing', True), ('data-dependent shapes', True), ('max dimensions', 64)]
['float32', 'float64']
True cpu (3, 2)
ValueError - Version "2099.01" of the Array API Standard is not supported.
2025.12
The capabilities dictionary matters for portability. NumPy supports boolean indexing and data-dependent output shapes (x[x > 0], np.unique_values), which the standard treats as optional because compiled or lazy libraries, such as JAX under jit, cannot support them. Code that must run there should avoid such operations or check the capabilities.
Writing code that works on any array library
The recipe is to get the namespace from the argument instead of importing NumPy, and to use only functions, not methods, that the standard defines.
import numpy as np
import array_api_strict as strict # pip install array-api-strict
def standardize(x):
"""Scale to zero mean and unit variance along the last axis, for any array library."""
xp = x.__array_namespace__(api_version="2024.12")
mean = xp.mean(x, axis=-1, keepdims=True)
std = xp.std(x, axis=-1, keepdims=True)
return (x - mean) / std
def softmax(x, axis=-1):
xp = x.__array_namespace__(api_version="2024.12")
z = x - xp.max(x, axis=axis, keepdims=True)
e = xp.exp(z)
return e / xp.sum(e, axis=axis, keepdims=True)
data = [[1.0, 2.0, 3.0], [10.0, 20.0, 30.0]]
for xp in (np, strict):
x = xp.asarray(data)
print(xp.__name__, "->", type(standardize(x)).__name__)
print(np.asarray(standardize(x)).round(3).tolist())
print(np.asarray(softmax(x)).round(3).tolist())
# What array-api-strict rejects, and NumPy tolerates
x = strict.asarray([[1.0, 2.0], [3.0, 4.0]])
for label, call in {
"x.sum()": lambda: x.sum(),
"x[[0, 1]]": lambda: x[[0, 1]],
"x + strict.asarray([1, 2])": lambda: x + strict.asarray([1, 2]),
"strict.asarray([1, 2]) + 1.5": lambda: strict.asarray([1, 2]) + 1.5,
}.items():
try:
call()
except Exception as exc:
print(label, "->", type(exc).__name__ + ":", str(exc)[:70])
Output:
numpy -> ndarray [[-1.225, 0.0, 1.225], [-1.225, 0.0, 1.225]] [[0.09, 0.245, 0.665], [0.0, 0.0, 1.0]] array_api_strict -> Array [[-1.225, 0.0, 1.225], [-1.225, 0.0, 1.225]] [[0.09, 0.245, 0.665], [0.0, 0.0, 1.0]] x.sum() -> AttributeError: 'Array' object has no attribute 'sum' x[[0, 1]] -> IndexError: Single-axes index [0, 1] has type(i)=<class 'list'>, but only integers x + strict.asarray([1, 2]) -> TypeError: array_api_strict.float64 and array_api_strict.int64 cannot be type pro strict.asarray([1, 2]) + 1.5 -> TypeError: Python float scalars can only be promoted with floating-point arrays.
Source: array-api-strict documentation
The same two functions ran unchanged on a NumPy array and on the reference implementation. The failures at the end show what portable code must avoid, all of which NumPy accepts:
-
Methods such as
x.sum(): usexp.sum(x). The standard defines operators and a few attributes on the array, but reductions are functions. -
Indexing with a list of integers: use an integer array and
xp.take, or slices. -
Mixing dtype families (integer with float) implicitly: convert with
xp.astypefirst. A Python float can only be combined with a floating array.
Choose array-api-strict for tests: it implements the standard and nothing else, so a test that passes on it proves the code does not rely on NumPy-specific behaviour. Add the real backends you support (CuPy, PyTorch, JAX) to the same parametrised test; testing practice is covered in Python Testing.
array-api-compat
array-api-compat is a small library that makes NumPy, CuPy, PyTorch, Dask and JAX arrays follow the standard more closely, including NumPy versions older than 2.0. Its array_namespace(x) helper returns a wrapper namespace and also accepts several arrays at once; on NumPy 2.5.4 it returned array_api_compat.numpy, a thin wrapper around NumPy, rather than numpy itself. It also offers helpers such as is_numpy_array, device and size that work across libraries (on a NumPy array, device returned cpu). Use it when you need to support NumPy 1.x, Dask or other libraries that deviate from the standard; for NumPy 2 plus conforming libraries, x.__array_namespace__() is enough and avoids an extra dependency.
Moving data between libraries
The standard’s exchange mechanism is DLPack: xp.from_dlpack(x, /, *, device=None, copy=None) creates an array of library xp from any object with __dlpack__, as described in Interoperability: Protocols and DLPack. NumPy can only represent CPU data, so importing a GPU tensor requires device="cpu" and a copy. The standard also specifies behaviours that differ from classic NumPy, such as no implicit mixing of arrays from different libraries and no automatic device transfers.
Source: Python array API standard
Who uses it?
-
scikit-learn can run some estimators on array API inputs when
array_api_dispatchis enabled; the status is experimental. See Array API and GPU Support (experimental). -
SciPy supports it for selected modules. According to the SciPy documentation the support is still experimental and hidden behind the environment variable
SCIPY_ARRAY_API=1, which also turns on stricter input validation (for examplenp.matrix, masked arrays and object arrays are rejected). Coverage varies a lot between modules and backends. -
CuPy, PyTorch and JAX each provide an array API compatible namespace, in some cases via array-api-compat.
Pitfalls
-
Do not import
numpy.array_api. It was removed in NumPy 2.0. -
The standard is a minimum. A function that runs on
array-api-strictis portable, but a NumPy-only function (for examplenp.nanmean,np.wherewith one argument or most ofnp.ma) simply does not exist elsewhere. -
Standard names are not always the names you know: books that predate NumPy 2 use
concatenate,transpose,powerandarccos, which still exist but are not portable. -
Never assume the default integer or float width across libraries. Request dtypes explicitly with
xp.asarray(data, dtype=xp.float64), and read defaults fromxp.__array_namespace_info__(). -
Do not combine arrays of different libraries in one expression. Convert at the boundary with
from_dlpackand decide where the data lives.