_add_docstring.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """A module for creating docstrings for sphinx ``data`` domains."""
  2. import re
  3. import textwrap
  4. _docstrings_list = []
  5. def add_newdoc(name, value, doc):
  6. _docstrings_list.append((name, value, doc))
  7. def _parse_docstrings():
  8. type_list_ret = []
  9. for name, value, doc in _docstrings_list:
  10. s = textwrap.dedent(doc).replace("\n", "\n ")
  11. # Replace sections by rubrics
  12. lines = s.split("\n")
  13. new_lines = []
  14. indent = ""
  15. for line in lines:
  16. m = re.match(r'^(\s+)[-=]+\s*$', line)
  17. if m and new_lines:
  18. prev = textwrap.dedent(new_lines.pop())
  19. if prev == "Examples":
  20. indent = ""
  21. new_lines.append(f'{m.group(1)}.. rubric:: {prev}')
  22. else:
  23. indent = 4 * " "
  24. new_lines.append(f'{m.group(1)}.. admonition:: {prev}')
  25. new_lines.append("")
  26. else:
  27. new_lines.append(f"{indent}{line}")
  28. s = "\n".join(new_lines)
  29. # Done.
  30. type_list_ret.append(f""".. data:: {name}\n :value: {value}\n {s}""")
  31. return "\n".join(type_list_ret)
  32. add_newdoc('ArrayLike', 'typing.Union[...]',
  33. """
  34. A `~typing.Union` representing objects that can be coerced into an `~numpy.ndarray`.
  35. Among others this includes the likes of:
  36. * Scalars.
  37. * (Nested) sequences.
  38. * Objects implementing the `~class.__array__` protocol.
  39. See Also
  40. --------
  41. :term:`array_like`:
  42. Any scalar or sequence that can be interpreted as an ndarray.
  43. Examples
  44. --------
  45. .. code-block:: python
  46. >>> import numpy as np
  47. >>> import numpy.typing as npt
  48. >>> def as_array(a: npt.ArrayLike) -> np.ndarray:
  49. ... return np.array(a)
  50. """)
  51. add_newdoc('DTypeLike', 'typing.Union[...]',
  52. """
  53. A `~typing.Union` representing objects that can be coerced into a `~numpy.dtype`.
  54. Among others this includes the likes of:
  55. * :class:`type` objects.
  56. * Character codes or the names of :class:`type` objects.
  57. * Objects with the ``.dtype`` attribute.
  58. See Also
  59. --------
  60. :ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
  61. A comprehensive overview of all objects that can be coerced into data types.
  62. Examples
  63. --------
  64. .. code-block:: python
  65. >>> import numpy as np
  66. >>> import numpy.typing as npt
  67. >>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
  68. ... return np.dtype(d)
  69. """)
  70. _docstrings = _parse_docstrings()