numpy 1.22.4 Pypi GitHub Homepage
Other Docs

To remove in the future –– numpy.typing

Typing (:mod:`numpy.typing`)

versionadded

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:

            <Unimplemented 'target' '.. _typing-extensions: https://pypi.org/project/typing-extensions/'>
           

Mypy plugin

versionadded
.. automodule:: numpy.typing.mypy_plugin
    
.. currentmodule:: numpy.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 :None:None:`ArrayLike` type tries to avoid creating object arrays. For example,

.. code-block:: python
    >>> 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:

.. code-block:: python
    >>> np.array(x**2 for x in range(10))  # type: ignore

or explicitly type the array like object as :None:None:`~typing.Any`:

.. code-block:: python
    >>> 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)

ndarray

It's possible to mutate the dtype of an array at runtime. For example, the following code is valid:

.. code-block:: python
    >>> x = np.array([1, 2])
    >>> x.dtype = np.bool_

This sort of mutation is not allowed by the types. Users who want to write statically typed code should instead use the :None:None:`numpy.ndarray.view` method to create a view of the array with a different dtype.

DTypeLike

The :None:None:`DTypeLike` type tries to avoid creation of dtype objects using dictionary of fields like below:

.. code-block:: python
    >>> 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 <arrays.dtypes>

Number precision

The precision of numpy.number subclasses is treated as a covariant generic parameter (see ~NBitBase ), simplifying the annotating of processes involving precision-based casting.

.. code-block:: python
    >>> 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]":
    ...     ...

Consequently, the likes of ~numpy.float16 , ~numpy.float32 and ~numpy.float64 are still sub-types of ~numpy.floating , but, contrary to runtime, they're not necessarily considered as sub-classes.

Timedelta64

The ~numpy.timedelta64 class is not considered a subclass of ~numpy.signedinteger , the former only inheriting from ~numpy.generic while static type checking.

0D arrays

During runtime numpy aggressively casts any passed 0D arrays into their corresponding ~numpy.generic instance. Until the introduction of shape typing (see Pep 646) it is unfortunately not possible to make the necessary distinction between 0D and >0D arrays. While thus not strictly correct, all operations are that can potentially perform a 0D-array -> scalar cast are currently annotated as exclusively returning an ndarray .

If it is known in advance that an operation _will_ perform a 0D-array -> scalar cast, then one can consider manually remedying the situation with either typing.cast or a # type: ignore comment.

Record array dtypes

The dtype of numpy.recarray , and the numpy.rec functions in general, can be specified in one of two ways:

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.

API

.. data:: ArrayLike
    ('value', 'typing.Union[...]')
    A `~typing.Union` representing objects that can be coerced
    into an `~numpy.ndarray`.

    Among others this includes the likes of:

    * Scalars.
    * (Nested) sequences.
    * Objects implementing the `~class.__array__` protocol.

    .. versionadded:: 1.20

    .. admonition:: See Also

        :term:`array_like`:
            Any scalar or sequence that can be interpreted as an ndarray.

    .. rubric:: Examples

    .. code-block:: python

        >>> import numpy as np
        >>> import numpy.typing as npt

        >>> def as_array(a: npt.ArrayLike) -> np.ndarray:
        ...     return np.array(a)
.. data:: DTypeLike
    ('value', 'typing.Union[...]')
    A `~typing.Union` representing objects that can be coerced
    into a `~numpy.dtype`.

    Among others this includes the likes of:

    * :class:`type` objects.
    * Character codes or the names of :class:`type` objects.
    * Objects with the ``.dtype`` attribute.

    .. versionadded:: 1.20

    .. admonition:: See Also

        :ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
            A comprehensive overview of all objects that can be coerced
            into data types.

    .. rubric:: Examples

    .. code-block:: python

        >>> import numpy as np
        >>> import numpy.typing as npt

        >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
        ...     return np.dtype(d)
.. data:: NDArray
    ('value', 'numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]')
    A :term:`generic <generic type>` version of
    `np.ndarray[Any, np.dtype[+ScalarType]] <numpy.ndarray>`.

    Can be used during runtime for typing arrays with a given dtype
    and unspecified shape.

    .. versionadded:: 1.21

    .. rubric:: Examples

    .. code-block:: python

        >>> import numpy as np
        >>> import numpy.typing as npt

        >>> print(npt.NDArray)
        numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]

        >>> print(npt.NDArray[np.float64])
        numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]

        >>> NDArrayInt = npt.NDArray[np.int_]
        >>> a: NDArrayInt = np.arange(10)

        >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
        ...     return np.array(a)
.. autoclass:: numpy.typing.NBitBase
    

Examples

See :

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


GitHub : /numpy/typing/__init__.py#0
type: <class 'module'>
Commit: