_add_docstring.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """A module for creating docstrings for sphinx ``data`` domains."""
  2. import re
  3. import textwrap
  4. from ._generic_alias import NDArray
  5. _docstrings_list = []
  6. def add_newdoc(name: str, value: str, doc: str) -> None:
  7. """Append ``_docstrings_list`` with a docstring for `name`.
  8. Parameters
  9. ----------
  10. name : str
  11. The name of the object.
  12. value : str
  13. A string-representation of the object.
  14. doc : str
  15. The docstring of the object.
  16. """
  17. _docstrings_list.append((name, value, doc))
  18. def _parse_docstrings() -> str:
  19. """Convert all docstrings in ``_docstrings_list`` into a single
  20. sphinx-legible text block.
  21. """
  22. type_list_ret = []
  23. for name, value, doc in _docstrings_list:
  24. s = textwrap.dedent(doc).replace("\n", "\n ")
  25. # Replace sections by rubrics
  26. lines = s.split("\n")
  27. new_lines = []
  28. indent = ""
  29. for line in lines:
  30. m = re.match(r'^(\s+)[-=]+\s*$', line)
  31. if m and new_lines:
  32. prev = textwrap.dedent(new_lines.pop())
  33. if prev == "Examples":
  34. indent = ""
  35. new_lines.append(f'{m.group(1)}.. rubric:: {prev}')
  36. else:
  37. indent = 4 * " "
  38. new_lines.append(f'{m.group(1)}.. admonition:: {prev}')
  39. new_lines.append("")
  40. else:
  41. new_lines.append(f"{indent}{line}")
  42. s = "\n".join(new_lines)
  43. s_block = f""".. data:: {name}\n :value: {value}\n {s}"""
  44. type_list_ret.append(s_block)
  45. return "\n".join(type_list_ret)
  46. add_newdoc('ArrayLike', 'typing.Union[...]',
  47. """
  48. A `~typing.Union` representing objects that can be coerced
  49. into an `~numpy.ndarray`.
  50. Among others this includes the likes of:
  51. * Scalars.
  52. * (Nested) sequences.
  53. * Objects implementing the `~class.__array__` protocol.
  54. .. versionadded:: 1.20
  55. See Also
  56. --------
  57. :term:`array_like`:
  58. Any scalar or sequence that can be interpreted as an ndarray.
  59. Examples
  60. --------
  61. .. code-block:: python
  62. >>> import numpy as np
  63. >>> import numpy.typing as npt
  64. >>> def as_array(a: npt.ArrayLike) -> np.ndarray:
  65. ... return np.array(a)
  66. """)
  67. add_newdoc('DTypeLike', 'typing.Union[...]',
  68. """
  69. A `~typing.Union` representing objects that can be coerced
  70. into a `~numpy.dtype`.
  71. Among others this includes the likes of:
  72. * :class:`type` objects.
  73. * Character codes or the names of :class:`type` objects.
  74. * Objects with the ``.dtype`` attribute.
  75. .. versionadded:: 1.20
  76. See Also
  77. --------
  78. :ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
  79. A comprehensive overview of all objects that can be coerced
  80. into data types.
  81. Examples
  82. --------
  83. .. code-block:: python
  84. >>> import numpy as np
  85. >>> import numpy.typing as npt
  86. >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
  87. ... return np.dtype(d)
  88. """)
  89. add_newdoc('NDArray', repr(NDArray),
  90. """
  91. A :term:`generic <generic type>` version of
  92. `np.ndarray[Any, np.dtype[+ScalarType]] <numpy.ndarray>`.
  93. Can be used during runtime for typing arrays with a given dtype
  94. and unspecified shape.
  95. .. versionadded:: 1.21
  96. Examples
  97. --------
  98. .. code-block:: python
  99. >>> import numpy as np
  100. >>> import numpy.typing as npt
  101. >>> print(npt.NDArray)
  102. numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]
  103. >>> print(npt.NDArray[np.float64])
  104. numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
  105. >>> NDArrayInt = npt.NDArray[np.int_]
  106. >>> a: NDArrayInt = np.arange(10)
  107. >>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
  108. ... return np.array(a)
  109. """)
  110. _docstrings = _parse_docstrings()