Typing (numpy.typing)#
Large parts of the NumPy API have PEP 484-style type annotations. In addition a number of type aliases are available to users, most prominently the two below:
ArrayLike: objects that can be converted to arraysDTypeLike: objects that can be converted to dtypes
See the user guide on static typing.
Differences from the runtime NumPy API#
NumPy is very flexible. Trying to describe the full range of possibilities statically would result in types that are not very helpful. For that reason, the typed NumPy API is often stricter than the runtime NumPy API. This section describes some notable differences.
ArrayLike#
The ArrayLike type tries to avoid creating object arrays. For
example,
>>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at ...>, dtype=object)
is valid NumPy code which will create a 0-dimensional object
array. Type-checkers will complain about the above example when using
the NumPy types however. If you really intended to do the above, then
you can either use a # type: ignore comment:
>>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as Any:
>>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at ...>, dtype=object)
DTypeLike#
The DTypeLike type tries to avoid creation of dtype objects using
dictionary of fields like below:
>>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
Although this is valid NumPy code, the type-checker will complain about it, since its usage is discouraged. Please see : Data type objects
Number precision#
The precision of numpy.number subclasses is treated as an invariant generic
parameter (see NBitBase), simplifying the annotating of processes
involving precision-based casting.
>>> from typing import TypeVar
>>> import numpy as np
>>> import numpy.typing as npt
>>> T = TypeVar("T", bound=npt.NBitBase)
>>> def func(a: np.floating[T], b: np.floating[T]) -> np.floating[T]:
... ...
Deprecated since version 2.3: The NBitBase helper is deprecated and will be
removed in a future release. Prefer expressing precision relationships via
typing.overload or TypeVar definitions bounded by concrete scalar
classes. For example:
from typing import TypeVar import numpy as np S = TypeVar("S", bound=np.floating) def func(a: S, b: S) -> S: ...or in the case of different input types mapping to different output types:
from typing import overload
import numpy as np
@overload
def phase(x: np.complex64) -> np.float32: ...
@overload
def phase(x: np.complex128) -> np.float64: ...
@overload
def phase(x: np.clongdouble) -> np.longdouble: ...
def phase(x: np.complexfloating) -> np.floating:
...
Timedelta64#
The timedelta64 class is not considered a subclass of
signedinteger, the former only inheriting from generic
while static type checking.
Record array dtypes#
The dtype of numpy.recarray, and the Creating record arrays
functions in general, can be specified in one of two ways:
Directly via the
dtypeargument.With up to five helper arguments that operate via
numpy.rec.format_parser:formats,names,titles,alignedandbyteorder.
These two approaches are currently typed as being mutually exclusive,
i.e. if dtype is specified than one may not specify formats.
While this mutual exclusivity is not (strictly) enforced during runtime,
combining both dtype specifiers can lead to unexpected or even downright
buggy behavior.
Scalar type sizes#
NumPy’s stubs assume a 64-bit platform, and a 32-bit C int:
Scalar types |
Type-checkers see |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
np.long and np.ulong depend on sys.platform.
On 32-bit platforms, np.intp, np.int_, np.long, and their unsigned
counterparts are 32-bit at runtime. On the rare platforms where C int isn’t
32-bit, np.intc and np.uintc have a different size. On these platforms, the
types above are incorrect.
The sizes of np.longdouble and
np.clongdouble depend on the platform, so they are separate
types, not aliases of other scalar types. np.float96, np.float128,
np.complex192, and np.complex256 are aliases of these two types. The stubs
always define all four, but at runtime a platform has at most one of np.float96
and np.float128, and at most one of np.complex192 and np.complex256. For
example, x86-64 Linux has np.float128 but not np.float96. On some platforms,
such as Windows and arm64 macOS, np.longdouble is a 64-bit float, like
np.float64, and none of the four aliases exist. Type-checkers still treat
np.longdouble and np.float64 as different types there.
Supported type-checkers#
NumPy’s stubs follow the Python typing specification, rather than the behavior of a specific type-checker, and support all modern type-checkers. No plugins are needed.
Where a type-checker deviates from the typing specification in a way that would degrade inference, the stubs can contain workarounds, such as a specific order of overloads, or extra overloads for a specific type-checker. This explains some unusual overloads in the stubs.
These deviations can also affect your code. For example, if an argument is
(partially) Any, several overloads can match it. If several of these remain after
the specification’s filtering steps, and their return types aren’t equivalent, the
call is ambiguous (see overload call evaluation). The specification then requires
a result type that is assignable to each of these return types, such as Any. Some
type-checkers pick the first matching overload instead, so type-checkers can infer
different types, especially for arrays with an unknown dtype. Arrays with a known
dtype avoid most of these differences.
If you find an incorrect type, or type-checkers that disagree about a type, please open an issue.
API#
ndarray
The numpy.ndarray class is a generic type that accepts two type arguments:
The type of
numpy.ndarray.shape, which must be a tuple of int, e.g.tuple[int, int](2-D shape) ortuple[()](0-D shape). The default shape istuple[Any, ...], which represents an unknown shape with any number of dimensions. Currently,Literalints or other more specific types are not supported.The type of
numpy.ndarray.dtype, which must be a subtype ofnumpy.dtypesuch asnumpy.dtype[numpy.float64]. If omitted, it will default tonumpy.dtype[Any].
>>> import numpy as np
>>> type ImageRGB = np.ndarray[tuple[int, int, int], np.dtype[np.uint8]]
>>> type Vector[S: np.generic] = np.ndarray[tuple[int], np.dtype[S]]
- numpy.typing.ArrayLike = typing.Union[...]#
A
Unionrepresenting objects that can be coerced into anndarray.Among others this includes the likes of:
Scalars.
(Nested) sequences.
Objects implementing the __array__ protocol.
See Also
- array_like:
Any scalar or sequence that can be interpreted as an ndarray.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> def as_array(a: npt.ArrayLike) -> np.ndarray: ... return np.array(a)
- numpy.typing.DTypeLike = typing.Union[...]#
A
Unionrepresenting objects that can be coerced into adtype.Among others this includes the likes of:
See Also
- Specifying and constructing data types
A comprehensive overview of all objects that can be coerced into data types.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> def as_dtype(d: npt.DTypeLike) -> np.dtype: ... return np.dtype(d)
- numpy.typing.NDArray[ST: generic]#
A generic type alias for arrays with a given dtype and unspecified shape.
type NDArray[ST: generic] = ndarray[tuple[Any, ...], dtype[ST]]
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> print(npt.NDArray) NDArray >>> print(npt.NDArray[np.float64]) NDArray[numpy.float64] >>> NDArrayInt = npt.NDArray[np.int_] >>> a: NDArrayInt = np.arange(10) >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]: ... return np.array(a)
- numpy.typing.Array0D[ST: generic]#
A 0-d
NDArraygeneric type alias.type Array0D[ST: generic] = ndarray[tuple[()], dtype[ST]]
Added in version 2.6.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> x: npt.Array0D[np.float64] = np.array(3.14)
- numpy.typing.Array1D[ST: generic]#
A 1-d
NDArraygeneric type alias.type Array1D[ST: generic] = ndarray[tuple[int], dtype[ST]]
Added in version 2.6.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> t: npt.Array1D[np.float64] = np.linspace(0, 1, 5)
- numpy.typing.Array2D[ST: generic]#
A 2-d
NDArraygeneric type alias.type Array2D[ST: generic] = ndarray[tuple[int, int], dtype[ST]]
Added in version 2.6.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> m: npt.Array2D[np.float64] = np.eye(3)
- numpy.typing.Array3D[ST: generic]#
A 3-d
NDArraygeneric type alias.type Array3D[ST: generic] = ndarray[tuple[int, int, int], dtype[ST]]
Added in version 2.6.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> rgb: npt.Array3D[np.uint8] = np.zeros((480, 640, 3), dtype=np.uint8)
- numpy.typing.Array4D[ST: generic]#
A 4-d
NDArraygeneric type alias.type Array4D[ST: generic] = ndarray[tuple[int, int, int, int], dtype[ST]]
Added in version 2.6.
Examples
>>> import numpy as np >>> import numpy.typing as npt >>> rgb_gif: npt.Array4D[np.uint8] = np.zeros((8, 480, 640, 3), dtype=np.uint8)
- class numpy.typing.NBitBase[source]#
A type representing
numpy.numberprecision during static type checking.Used exclusively for the purpose of static type checking,
NBitBaserepresents the base of a hierarchical set of subclasses. Each subsequent subclass is herein used for representing a lower level of precision, e.g.64Bit > 32Bit > 16Bit.Deprecated since version 2.3: Use
@typing.overloador aTypeVarwith a scalar-type as upper bound, instead.Examples
Below is a typical usage example:
NBitBaseis herein used for annotating a function that takes a float and integer of arbitrary precision as arguments and returns a new float of whichever precision is largest (e.g.np.float16 + np.int64 -> np.float64).>>> from typing import TYPE_CHECKING >>> import numpy as np >>> import numpy.typing as npt >>> def add[S: npt.NBitBase, T: npt.NBitBase]( ... a: np.floating[S], b: np.integer[T] ... ) -> np.floating[S | T]: ... return a + b >>> a = np.float16() >>> b = np.int64() >>> out = add(a, b) >>> if TYPE_CHECKING: ... reveal_locals() ... # note: Revealed local types are: ... # note: a: numpy.floating[numpy.typing._16Bit*] ... # note: b: numpy.signedinteger[numpy.typing._64Bit*] ... # note: out: numpy.floating[numpy.typing._64Bit*]