Type hints (PEP 484) support for the Sphinx autodoc extension
Project description
sphinx-autodoc-typehints
This Sphinx extension reads your Python type hints and automatically adds type information to your generated documentation -- so you write types once in code and they appear in your docs without duplication.
Features:
- Adds parameter and return types from annotations into docstrings
- Resolves types from
TYPE_CHECKINGblocks and.pyistub files - Renders
@overloadsignatures in docstrings - Extracts types from attrs and dataclass classes
- Shows default parameter values alongside types
- Controls union display style (
Union[X, Y]vsX | Y) - Automatically fixes cross-references for stdlib types whose runtime module differs from their documented path
- Supports custom type formatters and module name rewriting
- Extracts descriptions from
Annotated[T, Doc(...)]metadata - Works with Google and NumPy docstring styles
Sphinx has a built-in
autodoc_typehints
setting (since v2.1) that can move type hints between signatures and descriptions. This extension replaces that with the
features above. See Avoid duplicate types with built-in Sphinx.
- Installation
- Quick start
- How-to guides
- Avoid duplicate types with built-in Sphinx
- Use with Google or NumPy docstring style
- Control return type display
- Change how union types look
- Show default parameter values
- Control overload signature display
- Keep type hints in function signatures
- Handle circular imports
- Resolve types from
TYPE_CHECKINGblocks - Show types for
attrsordataclassfields - Write a custom type formatter
- Document a
NewTypeortypealias without expanding it - Add types for C extensions or packages without annotations
- Fix cross-reference links for stdlib types
- Fix cross-reference links for renamed modules
- Suppress warnings
- Reference
- Explanation
Installation
pip install sphinx-autodoc-typehints
Then add the extension to your conf.py:
extensions = ["sphinx.ext.autodoc", "sphinx_autodoc_typehints"]
Quick start
Instead of writing types in your docstrings, write them as Python type hints. The extension picks them up and adds them to your Sphinx output:
# Before: types repeated in docstrings
def format_unit(value, unit):
"""
Format a value with its unit.
:param float value: a numeric value
:param str unit: the unit (kg, m, etc.)
:rtype: str
"""
return f"{value} {unit}"
# After: types only in annotations, docs generated automatically
def format_unit(value: float, unit: str) -> str:
"""
Format a value with its unit.
:param value: a numeric value
:param unit: the unit (kg, m, etc.)
"""
return f"{value} {unit}"
The extension adds the type information to your docs during the Sphinx build. See an example at the pyproject-api docs.
How-to guides
Avoid duplicate types with built-in Sphinx
If types appear twice in your docs, you're likely running both this extension and Sphinx's built-in type hint
processing. Set
autodoc_typehints = "none"
in your conf.py to let this extension handle everything:
autodoc_typehints = "none"
Use with Google or NumPy docstring style
If you use sphinx.ext.napoleon for Google-style
or NumPy-style docstrings, load it before this extension:
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx_autodoc_typehints",
]
To avoid duplicate return type entries, disable the return type block in both extensions:
napoleon_use_rtype = False # sphinx.ext.napoleon setting
typehints_use_rtype = False
See
napoleon_use_rtype
in the Sphinx docs.
Control return type display
By default, return types appear as a separate block in your docs. You can change this:
# Don't show return types at all
typehints_document_rtype = False
# Don't show "None" return types, but show all others
typehints_document_rtype_none = False
# Show the return type inline with the return description
# instead of as a separate block
typehints_use_rtype = False
Change how union types look
By default, union types display as Union[str, int] and Optional[str]. To use the shorter pipe syntax (str | int,
str | None):
always_use_bars_union = True
On Python 3.14+, the pipe syntax is always used regardless of this setting.
By default, Optional[Union[A, B]] is simplified to Union[A, B, None]. To keep the Optional wrapper:
simplify_optional_unions = False
Note: with this set to False, any union containing None will display as Optional.
Show default parameter values
To include default values in your docs, set typehints_defaults to one of three styles:
# "param (int, default: 1) -- description"
typehints_defaults = "comma"
# "param (int) -- description (default: 1)"
typehints_defaults = "braces"
# "param (int) -- description (default: 1)" (at end of text)
typehints_defaults = "braces-after"
Control overload signature display
When a function has @overload signatures, they are
rendered automatically in the docstring. To disable this globally:
typehints_document_overloads = False
To disable overloads for a single function while keeping them everywhere else, add :no-overloads: to the docstring:
@overload
def f(x: int) -> str: ...
@overload
def f(x: str) -> bool: ...
def f(x):
""":no-overloads:
f accepts int or str, see docs for details.
"""
The :no-overloads: directive is stripped from the rendered output.
Keep type hints in function signatures
By default, type hints are removed from function signatures and shown in the parameter list below. To keep them visible in the signature line:
typehints_use_signature = True # show parameter types in signature
typehints_use_signature_return = True # show return type in signature
Handle circular imports
When two modules need to reference each other's types, you'll get circular import errors. Fix this by using
from __future__ import annotations, which makes
all type hints strings that are resolved later:
from __future__ import annotations
import othermodule
def process(item: othermodule.OtherClass) -> None: ...
Resolve types from TYPE_CHECKING blocks
This extension automatically imports types from
TYPE_CHECKING blocks at doc-build time. If a
type still fails to resolve, the dependency is likely not installed in your docs environment. Either install it, or
suppress the warning:
suppress_warnings = ["sphinx_autodoc_typehints.guarded_import"]
Show types for attrs or dataclass fields
The extension backfills annotations from attrs field metadata automatically. For
dataclasses, annotations are read from the class body. Make sure
the class is documented with .. autoclass:: and :members: or :undoc-members:.
Write a custom type formatter
To control exactly how a type appears in your docs, provide a formatter function. It receives the type annotation and
the Sphinx config, and returns RST markup (or
None to use the default rendering):
def my_formatter(annotation, config):
if annotation is bool:
return ":class:`bool`"
return None
typehints_formatter = my_formatter
To always show the full module path for types (e.g., collections.OrderedDict instead of OrderedDict):
typehints_fully_qualified = True
Document a NewType or type alias without expanding it
The extension preserves alias names only when they have a .. py:type:: directive in your docs. Without that entry, the
alias is expanded to its underlying type. Add a documentation entry for the alias, and it will render as a clickable
link instead.
Add types for C extensions or packages without annotations
The extension reads .pyi stub files
automatically. Place a .pyi file next to the .so/.pyd file (or as __init__.pyi in the package directory) with
the type annotations, and they'll be picked up.
Fix cross-reference links for stdlib types
Many Python stdlib classes have a __module__ that points to an internal module rather than their public documented
path. For example, threading.local reports its module as _thread._local, and concurrent.futures.Executor as
concurrent.futures._base.Executor. This produces broken cross-reference links because the extension builds links from
__module__.__qualname__.
When intersphinx is enabled, the extension automatically fixes this. After intersphinx loads its inventories, it builds a reverse mapping from runtime paths to documented paths and applies it during annotation formatting. No configuration is needed — just make sure intersphinx is loaded:
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx_autodoc_typehints",
]
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
}
With this, a type hint like threading.local correctly links to threading.local in the Python docs instead of
producing a broken _thread._local reference.
Fix cross-reference links for renamed modules
Some third-party libraries expose types under a different module path than where they're documented. For example, GTK
types live at gi.repository.Gtk.Window in Python, but their docs list them as Gtk.Window. This causes broken
intersphinx links.
Use typehints_fixup_module_name to rewrite the module path before links are generated:
def fixup_module_name(module: str) -> str:
if module.startswith("gi.repository."):
return module.removeprefix("gi.repository.")
return module
typehints_fixup_module_name = fixup_module_name
Suppress warnings
To silence all warnings from this extension:
suppress_warnings = ["sphinx_autodoc_typehints"]
To suppress only specific warning types, see Warning categories for the full list.
Reference
Configuration options
| Option | Default | Description |
|---|---|---|
typehints_document_rtype |
True |
Show the return type in docs. |
typehints_document_rtype_none |
True |
Show return type when it's None. |
typehints_document_overloads |
True |
Show @overload signatures in docs. Use :no-overloads: in a docstring for per-function control. |
typehints_use_rtype |
True |
Show return type as a separate block. When False, it's inlined with the return description. |
always_use_bars_union |
False |
Use X | Y instead of Union[X, Y]. Always on for Python 3.14+. |
simplify_optional_unions |
True |
Flatten Optional[Union[A, B]] to Union[A, B, None]. |
typehints_defaults |
None |
Show default values: "comma", "braces", or "braces-after". |
typehints_use_signature |
False |
Keep parameter types in the function signature. |
typehints_use_signature_return |
False |
Keep the return type in the function signature. |
typehints_fully_qualified |
False |
Show full module path for types (e.g., module.Class not Class). |
always_document_param_types |
False |
Add types even for parameters that don't have a :param: entry in the docstring. |
typehints_formatter |
None |
A function (annotation, Config) -> str | None for custom type rendering. |
typehints_fixup_module_name |
None |
A function (str) -> str to rewrite module paths before generating cross-reference links. |
Warning categories
All warnings can be suppressed via Sphinx's
suppress_warnings in
conf.py:
| Category | When it's raised |
|---|---|
sphinx_autodoc_typehints |
Catch-all for every warning from this extension. |
sphinx_autodoc_typehints.comment |
A type comment (# type: ...) couldn't be parsed. |
sphinx_autodoc_typehints.forward_reference |
A forward reference (string annotation) couldn't be resolved. |
sphinx_autodoc_typehints.guarded_import |
A type from a TYPE_CHECKING block couldn't be imported at runtime. |
sphinx_autodoc_typehints.local_function |
A type annotation references a function defined inside another function. |
sphinx_autodoc_typehints.multiple_ast_nodes |
A type comment matched multiple definitions and the right one is ambiguous. |
Explanation
How it works
During the Sphinx build, this extension hooks into two
autodoc events.
First, it strips type annotations from function signatures (so they don't appear twice). Then, it reads the annotations
and adds type information into the docstring -- parameter types go next to each :param: entry, and the return type
becomes an :rtype: entry.
Only parameters that already have a :param: line in the docstring get type information added. Set
always_document_param_types = True to add types for all parameters, even undocumented ones.
How return type options interact
The return type options combine as follows:
- Both defaults (
typehints_document_rtype = True,typehints_use_rtype = True) -- return type appears as a separate:rtype:block below the description. - Inline mode (
typehints_document_rtype = True,typehints_use_rtype = False) -- return type is appended to the:return:text. If there's no:return:entry, it falls back to a separate block. - Disabled (
typehints_document_rtype = False) -- no return type shown, regardless of other settings. - Skip None (
typehints_document_rtype_none = False) -- hidesNonereturn types specifically, other return types still appear.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sphinx_autodoc_typehints-3.9.8.tar.gz.
File metadata
- Download URL: sphinx_autodoc_typehints-3.9.8.tar.gz
- Upload date:
- Size: 68.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1e36b31ee593b7e838988045918b7fa965f5062abbd6800af96d5e2c3f17130e
|
|
| MD5 |
aa062f4b49af75c1a4105a44fe5de448
|
|
| BLAKE2b-256 |
744d02216afa475c838c123b41f30e3a2875ad27c14fae3f5bbed4ba4e7fd894
|
Provenance
The following attestation bundles were made for sphinx_autodoc_typehints-3.9.8.tar.gz:
Publisher:
release.yaml on tox-dev/sphinx-autodoc-typehints
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sphinx_autodoc_typehints-3.9.8.tar.gz -
Subject digest:
1e36b31ee593b7e838988045918b7fa965f5062abbd6800af96d5e2c3f17130e - Sigstore transparency entry: 1066524822
- Sigstore integration time:
-
Permalink:
tox-dev/sphinx-autodoc-typehints@d725d6055434a82f7716dac5fa2e1ff43c7858d0 -
Branch / Tag:
refs/tags/3.9.8 - Owner: https://github.com/tox-dev
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@d725d6055434a82f7716dac5fa2e1ff43c7858d0 -
Trigger Event:
push
-
Statement type:
File details
Details for the file sphinx_autodoc_typehints-3.9.8-py3-none-any.whl.
File metadata
- Download URL: sphinx_autodoc_typehints-3.9.8-py3-none-any.whl
- Upload date:
- Size: 36.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
df123ec82479934fed27e31d4ccdcf382901c5d9481450fc224054496e574466
|
|
| MD5 |
5d1c951ba0a592c984d638289b8ff793
|
|
| BLAKE2b-256 |
a86cf275f59095b2fec6627c3ce2caba4e18f55a3925718cf0547cde04821a37
|
Provenance
The following attestation bundles were made for sphinx_autodoc_typehints-3.9.8-py3-none-any.whl:
Publisher:
release.yaml on tox-dev/sphinx-autodoc-typehints
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sphinx_autodoc_typehints-3.9.8-py3-none-any.whl -
Subject digest:
df123ec82479934fed27e31d4ccdcf382901c5d9481450fc224054496e574466 - Sigstore transparency entry: 1066524824
- Sigstore integration time:
-
Permalink:
tox-dev/sphinx-autodoc-typehints@d725d6055434a82f7716dac5fa2e1ff43c7858d0 -
Branch / Tag:
refs/tags/3.9.8 - Owner: https://github.com/tox-dev
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yaml@d725d6055434a82f7716dac5fa2e1ff43c7858d0 -
Trigger Event:
push
-
Statement type: