Skip to content

bagof.hints.numpy

Hints for numpy arrays and data types.

Note

This module is not imported by bagof.hints, so that importing the package never imports numpy. Import it explicitly:

from bagof.hints import numpy as npt

It stays importable when numpy is absent, in which case the array types degrade to empty generic stubs, so that annotations still evaluate.

Attributes

NDArray module-attribute

NDArray = ndarray[tx.Tuple[int, ...], dtype[DTYPE]]

An array of arbitrary shape, parametrised by its data type.

Note

Unlike numpy.typing.NDArray, which is generic over the scalar type only, this alias keeps both parameters of ndarray, so that ndarray[Tuple[int, int], dtype[float64]] and NDArray[float64] agree.

ArrayLike module-attribute

ArrayLike = npt.ArrayLike

DTypeLike module-attribute

DTypeLike = npt.DTypeLike

Classes

ArrayNamespace

Bases: Protocol

An object that implements the Python array API standard.

This is the modern, portable alternative to ArrayProtocol: rather than converting to a numpy array, it exposes the namespace of the library that owns the object, so that library-agnostic code can call xp.mean(x) without knowing which library x came from.

See https://data-apis.org/array-api/latest/.

Tip

Prefer this over ArrayProtocol when the goal is to stay in the originating library (and off the host, for GPU arrays), since __array__ forces a conversion to numpy.

ArrayProtocol

Bases: Protocol

An object that can be converted to an array.

This is the oldest and most widely implemented array hook: numpy, cupy, dask, torch and pandas objects all provide it, so a single structural check covers them all. See numpy.ndarray.__array__.

Example

>>> import numpy as np
>>> from bagof.hints.array import ArrayProtocol
>>> isinstance(np.array([1, 2, 3]), ArrayProtocol)
True
>>> isinstance([1, 2, 3], ArrayProtocol)
False

DTypeProtocol

Bases: Protocol[DTYPE]

An object that carries a data type.

Any array, and any numpy.dtype-like object, satisfies this. The parameter is the type of the dtype attribute itself; it is invariant, because the protocol declares a mutable attribute rather than a read-only property.

dtype

Bases: Generic[DTYPE]

A generic stub for numpy.dtype.

ndarray

Bases: Generic[SHAPE, DTYPE]

A generic stub for numpy.ndarray.