diff --git a/src/sphinx_autodoc_typehints/__init__.py b/src/sphinx_autodoc_typehints/__init__.py index d2b1b06..e67180f 100644 --- a/src/sphinx_autodoc_typehints/__init__.py +++ b/src/sphinx_autodoc_typehints/__init__.py @@ -354,9 +354,24 @@ def process_signature( # noqa: C901, PLR0913, PLR0917 obj = inspect.unwrap(obj) sph_signature = sphinx_signature(obj, type_aliases=app.config["autodoc_type_aliases"]) + typehints_formatter: Callable[..., str | None] | None = getattr(app.config, "typehints_formatter", None) + + def _get_formatted_annotation(annotation: TypeVar) -> TypeVar: + if typehints_formatter is None: + return annotation + formatted_name = typehints_formatter(annotation) + return annotation if not isinstance(formatted_name, str) else TypeVar(formatted_name) + + if app.config.typehints_use_signature_return: + sph_signature = sph_signature.replace( + return_annotation=_get_formatted_annotation(sph_signature.return_annotation) + ) if app.config.typehints_use_signature: - parameters = list(sph_signature.parameters.values()) + parameters = [ + param.replace(annotation=_get_formatted_annotation(param.annotation)) + for param in sph_signature.parameters.values() + ] else: parameters = [param.replace(annotation=inspect.Parameter.empty) for param in sph_signature.parameters.values()] diff --git a/tests/test_integration.py b/tests/test_integration.py index 3339916..93aa1e5 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1385,6 +1385,42 @@ def has_doctest1() -> None: """ +Unformatted = TypeVar("Unformatted") + + +@warns("cannot cache unpickable configuration value: 'typehints_formatter'") +@expected( + """ + mod.typehints_formatter_applied_to_signature(param: Formatted) -> Formatted + + Do nothing + + Parameters: + **param** (Formatted) -- A parameter + + Return type: + Formatted + + Returns: + The return value + """, + typehints_use_signature=True, + typehints_use_signature_return=True, + typehints_formatter=lambda _, __=None: "Formatted", +) +def typehints_formatter_applied_to_signature(param: Unformatted) -> Unformatted: + """ + Do nothing + + Args: + param: A parameter + + Returns: + The return value + """ + return param + + # Config settings for each test run. # Config Name: Sphinx Options as Dict. configs = {