Skip to main content

Type hints (PEP 484) support for the Sphinx autodoc extension

Project description

sphinx-autodoc-typehints

PyPI Supported Python versions Downloads check

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_CHECKING blocks and .pyi stub files
  • Renders @overload signatures in docstrings
  • Extracts types from attrs and dataclass classes
  • Shows default parameter values alongside types
  • Controls union display style (Union[X, Y] vs X | Y)
  • 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

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"

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 renamed modules

Some 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_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) -- hides None return 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

sphinx_autodoc_typehints-3.8.0.tar.gz (59.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sphinx_autodoc_typehints-3.8.0-py3-none-any.whl (32.6 kB view details)

Uploaded Python 3

File details

Details for the file sphinx_autodoc_typehints-3.8.0.tar.gz.

File metadata

  • Download URL: sphinx_autodoc_typehints-3.8.0.tar.gz
  • Upload date:
  • Size: 59.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for sphinx_autodoc_typehints-3.8.0.tar.gz
Algorithm Hash digest
SHA256 155a30407e88ed3287eeeb1e9156b0ed0ad08c998b0391c652b540563132fd70
MD5 3f67a406296d9d14a997ce78c919cb39
BLAKE2b-256 ba8972f96fe27aa1cfdc882aa6e1309a86b94e4653c1e8acf9b143d34e89c619

See more details on using hashes here.

Provenance

The following attestation bundles were made for sphinx_autodoc_typehints-3.8.0.tar.gz:

Publisher: release.yaml on tox-dev/sphinx-autodoc-typehints

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sphinx_autodoc_typehints-3.8.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sphinx_autodoc_typehints-3.8.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f348971f3d88eaee053668b61512e921086b8f0600f1e0887a39bc9476aca51c
MD5 47a6d2aa192c163d86bcb94291ad1ac0
BLAKE2b-256 8c0e36820830c766647d688dfc2b3fda76d76c1cf007eea58fffc1990195aca4

See more details on using hashes here.

Provenance

The following attestation bundles were made for sphinx_autodoc_typehints-3.8.0-py3-none-any.whl:

Publisher: release.yaml on tox-dev/sphinx-autodoc-typehints

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page