sphinx-autodoc-typehints icon indicating copy to clipboard operation
sphinx-autodoc-typehints copied to clipboard

typehints_formatter not applied to signature

Open aeisenbarth opened this issue 1 year ago • 1 comments

When type hints are shown in the signature, they are not passed through typehints_formatter.

Example

package
├── docs
│   ├── conf.py
│   └── index.rst
├── my_module
│   └── __init__.py
└── pyproject.toml

conf.py

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.napoleon",
    "sphinx_autodoc_typehints",
    "sphinx.ext.autosummary",
]

# sphinx.ext.napoleon
napoleon_use_rtype = typehints_use_rtype = False

# sphinx.ext.autodoc
# For this issue, this makes no difference regarding the signature, only regarding the description.
# Note that "description" and "both" add a separate "Return type" section which is also not
# formatted by typehints_formatter. 
autodoc_typehints = "both"

# sphinx.ext.autosummary
autosummary_generate = True

# sphinx_autodoc_typehints
typehints_document_rtype = False
typehints_use_signature = True
typehints_use_signature_return = True


def typehints_formatter(annotation, config):
    from typing import TypeVar

    if isinstance(annotation, TypeVar) and annotation.__name__ == "Unformatted":
        return "Formatted"

index.rst

.. autosummary::

   my_module.my_function

my_module/__init__.py

from typing import TypeVar

Unformatted = TypeVar("Unformatted")


def my_function(arg: Unformatted) -> Unformatted:
    """
    Do nothing

    Args:
        arg: An argument

    Returns:
        The argument returned
    """
    return arg

Expected behavior

  • Types are formatted everywhere:
    • Parameter types in signature (because typehints_use_signature = True)
    • Return type in signature (because typehints_use_signature_return = True)
    • Types in "Parameters" section of description (because autodoc_typehints = "both")
    • Types in "Returns" section of description (because autodoc_typehints = "both")
    • Types in "Return type" section of description, if shown (if napoleon_use_rtype = typehints_use_rtype = True)

Actual behavior

  • Parameter types in signature are not formatted.
  • Return type in signature is not formatted.

image

Versions

Platform:              linux; (Linux-5.15.0-91-generic-x86_64-with-glibc2.35)
Python version:        3.9.17 (main, Jul  5 2023, 20:41:20) 
[GCC 11.2.0])
Python implementation: CPython
Sphinx version:        7.2.6
Docutils version:      0.20.1
Jinja2 version:        3.1.2
Pygments version:      2.16.1
sphinx-autodoc-typehints: 2.0.0

aeisenbarth avatar Feb 23 '24 13:02 aeisenbarth

PR welcome to fix this bug 👍

gaborbernat avatar Feb 23 '24 22:02 gaborbernat