How to document types
It is also worth noting the old syntax :type parameter2: MyClass
for parameter type, also documented at https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#signatures
But with Python 3 typing
we can just:
main.py
class MyClass:
"""
This class does that.
"""
def __init__(self, i):
self.i = i
def do_this(parameter1: int, parameter2: MyClass):
"""
This function does this.
:param parameter1: my favorite int
:param parameter2: my favorite class
"""
return parameter1 + parameter2.i
build.sh
sphinx-build . out
conf.py
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
extensions = [ 'sphinx.ext.autodoc' ]
autodoc_default_options = {
'members': True,
}
index.rst
.. automodule:: main
requirements.txt
Sphinx==6.1.3
Output on out/index.html
:
Note how it correctly links the parameter type to the documentation of the class MyClass
.
Make types appear next to the description instead
Can be done by adding the following to your conf.py
:
autodoc_typehints = "description"
See also: How to make Sphinx show Python 3 typing type hints next to the argument description instead of on the function signature?
:type:
example
For reference, the pre-typing
approach looked like:
def do_this(parameter1, parameter2):
"""
This function does this.
:param parameter1: my favorite int
:type parameter1: int
:param parameter2: my favorite class
:type parameter2: MyClass
"""
return parameter1 + parameter2.i
which produces output identical to the autodoc_typehints = "description"
version with typing
, but with more duplication as we have to type (no pun) parameter1
and parameter2
yet again.
Other useful typing related things to know
Tested on Ubuntu 22.10, Python 3.10.7.