Skip to content

Commit 244af2f

Browse files
Apply typehints_formatter to signature (#494)
* 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>
1 parent e17a669 commit 244af2f

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

Diff for: src/sphinx_autodoc_typehints/__init__.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -354,9 +354,24 @@ def process_signature( # noqa: C901, PLR0913, PLR0917
354354

355355
obj = inspect.unwrap(obj)
356356
sph_signature = sphinx_signature(obj, type_aliases=app.config["autodoc_type_aliases"])
357+
typehints_formatter: Callable[..., str | None] | None = getattr(app.config, "typehints_formatter", None)
358+
359+
def _get_formatted_annotation(annotation: TypeVar) -> TypeVar:
360+
if typehints_formatter is None:
361+
return annotation
362+
formatted_name = typehints_formatter(annotation)
363+
return annotation if not isinstance(formatted_name, str) else TypeVar(formatted_name)
364+
365+
if app.config.typehints_use_signature_return:
366+
sph_signature = sph_signature.replace(
367+
return_annotation=_get_formatted_annotation(sph_signature.return_annotation)
368+
)
357369

358370
if app.config.typehints_use_signature:
359-
parameters = list(sph_signature.parameters.values())
371+
parameters = [
372+
param.replace(annotation=_get_formatted_annotation(param.annotation))
373+
for param in sph_signature.parameters.values()
374+
]
360375
else:
361376
parameters = [param.replace(annotation=inspect.Parameter.empty) for param in sph_signature.parameters.values()]
362377

Diff for: tests/test_integration.py

+36
Original file line numberDiff line numberDiff line change
@@ -1385,6 +1385,42 @@ def has_doctest1() -> None:
13851385
"""
13861386

13871387

1388+
Unformatted = TypeVar("Unformatted")
1389+
1390+
1391+
@warns("cannot cache unpickable configuration value: 'typehints_formatter'")
1392+
@expected(
1393+
"""
1394+
mod.typehints_formatter_applied_to_signature(param: Formatted) -> Formatted
1395+
1396+
Do nothing
1397+
1398+
Parameters:
1399+
**param** (Formatted) -- A parameter
1400+
1401+
Return type:
1402+
Formatted
1403+
1404+
Returns:
1405+
The return value
1406+
""",
1407+
typehints_use_signature=True,
1408+
typehints_use_signature_return=True,
1409+
typehints_formatter=lambda _, __=None: "Formatted",
1410+
)
1411+
def typehints_formatter_applied_to_signature(param: Unformatted) -> Unformatted:
1412+
"""
1413+
Do nothing
1414+
1415+
Args:
1416+
param: A parameter
1417+
1418+
Returns:
1419+
The return value
1420+
"""
1421+
return param
1422+
1423+
13881424
# Config settings for each test run.
13891425
# Config Name: Sphinx Options as Dict.
13901426
configs = {

0 commit comments

Comments
 (0)