Skip to content

Commit

Permalink
Apply typehints_formatter to signature
Browse files Browse the repository at this point in the history
  • Loading branch information
Priyansh121096 committed Oct 8, 2024
1 parent e17a669 commit f3f0c9c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/sphinx_autodoc_typehints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,9 +354,19 @@ 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):
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()]

Expand Down
35 changes: 35 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -1385,6 +1385,41 @@ 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 ann, cfg=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 = {
Expand Down

0 comments on commit f3f0c9c

Please sign in to comment.