Sphinx Autodoc Typehints
sphinx-autodoc-typehints is a Sphinx extension that provides full support for type hints (PEP 484) in the documentation generated by `sphinx.ext.autodoc`. It parses type annotations from Python code and renders them beautifully in reStructuredText or Markdown output. The current version is 3.9.11, and it follows a minor release cadence driven by bug fixes and compatibility with new Sphinx or Python versions.
Warnings
- breaking Version 3.0.0 and newer require Python 3.12+ and Sphinx 6.0+. If you are on an older Python version, you must use `sphinx-autodoc-typehints<3`.
- breaking Configuration options `always_document_param_types` and `typehints_fully_qualified` were removed in version 3.0.0. Using them will result in a Sphinx warning about unknown configuration values and these settings will be ignored.
- gotcha `sphinx.ext.autodoc` must be enabled and loaded *before* `sphinx_autodoc_typehints` in your `conf.py` `extensions` list for type hints to be correctly processed.
- gotcha The default value for the `typehints_document_rtype` configuration option changed from `True` to `False` in version 3.0.0. This means return types are no longer documented by default.
Install
-
pip install sphinx-autodoc-typehints
Imports
- sphinx_autodoc_typehints
extensions = [ 'sphinx.ext.autodoc', 'sphinx_autodoc_typehints' ]
Quickstart
import os
# conf.py example
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath.
import sys
sys.path.insert(0, os.path.abspath('.'))
project = 'My Project'
copyright = '2024, Author Name'
author = 'Author Name'
release = '0.1'
extensions = [
'sphinx.ext.autodoc',
'sphinx_autodoc_typehints' # Add this extension
]
# Optional: Configure the extension
typehints_fully_qualified = False # This option was removed in v3.0.0 (example of a common mistake for older configs)
typehints_document_rtype = True # Explicitly document return types
# Example Python module (my_module.py)
# def greet(name: str, age: int = 30) -> str:
# """Greets a person.
#
# :param name: The name of the person.
# :param age: The age of the person.
# :return: A greeting message.
# """
# return f"Hello, {name}! You are {age} years old."