Skip to content

Commit

Permalink
Apply typehints_formatter to signature (#494)
Browse files Browse the repository at this point in the history
* Apply typehints_formatter to signature

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix lint

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
Priyansh121096 and pre-commit-ci[bot] authored Oct 9, 2024
1 parent e17a669 commit 244af2f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/sphinx_autodoc_typehints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()]

Expand Down
36 changes: 36 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down

0 comments on commit 244af2f

Please sign in to comment.