diff options
author | Bas van Beek <b.f.van.beek@vu.nl> | 2020-11-23 19:19:08 +0100 |
---|---|---|
committer | Bas van Beek <b.f.van.beek@vu.nl> | 2020-11-24 13:34:03 +0100 |
commit | f12242a237e9bcc293ef2d0c3b81d0e04d06936a (patch) | |
tree | 5d5aaa931d98ba5ecc89bbeb0fda46aa328ad80c | |
parent | 94b347e867759325d8586ad3d1c3e01c590d83c1 (diff) | |
download | numpy-f12242a237e9bcc293ef2d0c3b81d0e04d06936a.tar.gz |
DOC: Update the `numpy.typing` documentation
-rw-r--r-- | numpy/typing/__init__.py | 66 | ||||
-rw-r--r-- | numpy/typing/_add_docstring.py | 96 |
2 files changed, 144 insertions, 18 deletions
diff --git a/numpy/typing/__init__.py b/numpy/typing/__init__.py index cbde75462..a9bf94f13 100644 --- a/numpy/typing/__init__.py +++ b/numpy/typing/__init__.py @@ -11,14 +11,11 @@ Typing (:mod:`numpy.typing`) typing-extensions_ package. Large parts of the NumPy API have PEP-484-style type annotations. In -addition, the following type aliases are available for users. +addition a number of type aliases are available to users, most prominently +the two below: -- ``typing.ArrayLike``: objects that can be converted to arrays -- ``typing.DTypeLike``: objects that can be converted to dtypes - -Roughly speaking, ``typing.ArrayLike`` is "objects that can be used as -inputs to ``np.array``" and ``typing.DTypeLike`` is "objects that can -be used as inputs to ``np.dtype``". +- `ArrayLike`: objects that can be converted to arrays +- `DTypeLike`: objects that can be converted to dtypes .. _typing-extensions: https://pypi.org/project/typing-extensions/ @@ -34,13 +31,13 @@ differences. ArrayLike ~~~~~~~~~ -The ``ArrayLike`` type tries to avoid creating object arrays. For +The `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 0x10c004cd0>, dtype=object) + 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 @@ -51,14 +48,14 @@ 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``: +or explicitly type the array like object as `~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 0x1192741d0>, dtype=object) + array(<generator object <genexpr> at ...>, dtype=object) ndarray ~~~~~~~ @@ -75,10 +72,10 @@ This sort of mutation is not allowed by the types. Users who want to write statically typed code should insted use the `numpy.ndarray.view` method to create a view of the array with a different dtype. -dtype -~~~~~ +DTypeLike +~~~~~~~~~ -The ``DTypeLike`` type tries to avoid creation of dtype objects using +The `DTypeLike` type tries to avoid creation of dtype objects using dictionary of fields like below: .. code-block:: python @@ -87,14 +84,41 @@ dictionary of fields like below: Although this is valid Numpy code, the type checker will complain about it, since its usage is discouraged. -Please see : https://numpy.org/devdocs/reference/arrays.dtypes.html +Please see : :ref:`Data type objects <arrays.dtypes>` + +Number Precision +~~~~~~~~~~~~~~~~ + +The precision of `numpy.number` subclasses is treated as a covariant generic +parameter (see :class:`~NBitBase`), simplifying the annoting of proccesses +involving precision-based casting. + +.. code-block:: python -NBitBase -~~~~~~~~ + >>> from typing import TypeVar + >>> import numpy as np + >>> import numpy.typing as npt -.. autoclass:: numpy.typing.NBitBase + >>> 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. + +API +--- """ +# NOTE: The API section will be appended with additional entries +# further down in this file from typing import TYPE_CHECKING @@ -186,6 +210,12 @@ from ._array_like import _SupportsArray, ArrayLike from ._shape import _Shape, _ShapeLike from ._dtype_like import _SupportsDType, _VoidDTypeLike, DTypeLike +if __doc__ is not None: + from ._add_docstring import _docstrings + __doc__ += _docstrings + __doc__ += f'\n.. autoclass:: numpy.typing.NBitBase\n' + del _docstrings + from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester diff --git a/numpy/typing/_add_docstring.py b/numpy/typing/_add_docstring.py new file mode 100644 index 000000000..8e39fe2c6 --- /dev/null +++ b/numpy/typing/_add_docstring.py @@ -0,0 +1,96 @@ +"""A module for creating docstrings for sphinx ``data`` domains.""" + +import re +import textwrap + +_docstrings_list = [] + + +def add_newdoc(name, value, doc): + _docstrings_list.append((name, value, doc)) + + +def _parse_docstrings(): + type_list_ret = [] + for name, value, doc in _docstrings_list: + s = textwrap.dedent(doc).replace("\n", "\n ") + + # Replace sections by rubrics + lines = s.split("\n") + new_lines = [] + indent = "" + for line in lines: + m = re.match(r'^(\s+)[-=]+\s*$', line) + if m and new_lines: + prev = textwrap.dedent(new_lines.pop()) + if prev == "Examples": + indent = "" + new_lines.append(f'{m.group(1)}.. rubric:: {prev}') + else: + indent = 4 * " " + new_lines.append(f'{m.group(1)}.. admonition:: {prev}') + new_lines.append("") + else: + new_lines.append(f"{indent}{line}") + s = "\n".join(new_lines) + + # Done. + type_list_ret.append(f""".. data:: {name}\n :value: {value}\n {s}""") + return "\n".join(type_list_ret) + + +add_newdoc('ArrayLike', '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. + + See Also + -------- + :term:`array_like`: + Any scalar or sequence that can be interpreted as an ndarray. + + 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) + + """) + +add_newdoc('DTypeLike', '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. + + See Also + -------- + :ref:`Specifying and constructing data types <arrays.dtypes.constructing>` + A comprehensive overview of all objects that can be coerced into data types. + + 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) + + """) + +_docstrings = _parse_docstrings() |