Skip to content

Commit 8112aed

Browse files
committed
Add recommendations on documenting generics.
1 parent 1f76c5d commit 8112aed

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

stack/documenting-code-with-type-annotations.rst

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,7 @@ A simple return type does not need backticks to create a link, but backticks may
7474
As always, types in docstrings do *not* respect imports in the file, and instead are resolved using the `Sphinx target-resolution rules`_.
7575
See :ref:`rst-python-link` for details.
7676

77-
Functions that return multiple values via a tuple should just have multiple
78-
entries::
77+
Functions that return multiple values via a tuple should just have multiple entries::
7978

8079
def return_pair() -> tuple[str, int]:
8180
"""Return a pair.
@@ -111,8 +110,33 @@ Their docstrings should continue to include the types parenthetically::
111110
included in documentation *at all*, except for those on `~dataclasses.dataclass` types.
112111
Important instance attributes that cannot have a class-level default value should be made into properties so they can be documented.
113112

113+
Generics
114+
--------
115+
116+
Functions that use `generics`_ will appear in the documentation with the type variable as the type, but these do not resolve to any kind of link, and in nitpick mode Sphinx will warn about those broken links.
117+
These should be included in the ``nitpick-ignore`` section of ``documenteer.toml``:
118+
119+
.. code-block:: toml
120+
[sphinx]
121+
nitpick_ignore = [
122+
["py:class", "T"], # type variables don't resolve
123+
]
124+
125+
for e.g.::
126+
127+
def generic[T: int | float](value: T) -> T:
128+
"""Do something with a value.
129+
130+
Parameters
131+
----------
132+
value
133+
The given value (a `float` or `int`).
134+
"""
135+
136+
Since the automatic docstrings do not include any information about a bound on the type variable (i.e. ``int | float`` here), including that information in the description is recommended.
114137

115138
.. _`Documenteer 2.x`: https://documenteer.lsst.io
116139
.. _`sphinx-autodoc-typehints`: https://pypi.org/project/sphinx-autodoc-typehints/
117140
.. _`pipelines.lsst.io`: https://pipelines.lsst.io
118141
.. _`Sphinx target-resolution rules`: <https://www.sphinx-doc.org/en/master/usage/domains/python.html#target-resolution>`
142+
.. _`generics`: <https://docs.python.org/3/library/typing.html#generics>

0 commit comments

Comments
 (0)