Skip to content

bagof.hints.array

Protocols for array-like objects, independent of any array library.

The protocols defined here are purely structural, so they match numpy, cupy, dask and any other array library that implements the relevant dunder method -- without importing, or depending on, any of them.

Library-specific hints live in the numpy, cupy and dask submodules. Unlike every other submodule, those are not imported by default, so that import bagof.hints never imports an array library.

Attributes

ArrayLike module-attribute

ArrayLike = tx.Union[numbers.Number, tx.Sequence[tx.Any], ArrayProtocol]

Anything that can reasonably be turned into an array.

Note

This is the library-agnostic fallback. When numpy is installed, bagof.hints.numpy.ArrayLike is more precise -- it additionally covers buffers, nested sequences, and the str/bytes cases.

DTypeLike module-attribute

DTypeLike = tx.Union[type, str, 'DTypeProtocol[tx.Any]']

Anything that can reasonably be turned into a data type.

Note

This is the library-agnostic fallback. When numpy is installed, bagof.hints.numpy.DTypeLike is more precise -- it additionally covers structured-dtype specifications such as [("a", int)].

Classes

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

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.

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.