Skip to content

Commit

Permalink
Add unqualified_typehints parameter to stringify_signature()
Browse files Browse the repository at this point in the history
To make the generated function signatures simple, this adds a new
parameter `unqualified_typehints` to sphinx.util.inspect:
stringify_signature() to suppress the leading module name of
typehints.
  • Loading branch information
tk0miya committed Dec 3, 2021
1 parent 80f79ae commit 5aa6cbb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 6 additions & 3 deletions sphinx/util/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,10 +744,13 @@ def evaluate(annotation: Any, globalns: Dict, localns: Dict) -> Any:


def stringify_signature(sig: inspect.Signature, show_annotation: bool = True,
show_return_annotation: bool = True) -> str:
show_return_annotation: bool = True,
unqualified_typehints: bool = False) -> str:
"""Stringify a Signature object.
:param show_annotation: Show annotation in result
:param unqualified_typehints: Show annotations as unqualified
(ex. io.StringIO -> StringIO)
"""
args = []
last_kind = None
Expand All @@ -771,7 +774,7 @@ def stringify_signature(sig: inspect.Signature, show_annotation: bool = True,

if show_annotation and param.annotation is not param.empty:
arg.write(': ')
arg.write(stringify_annotation(param.annotation))
arg.write(stringify_annotation(param.annotation, unqualified_typehints))
if param.default is not param.empty:
if show_annotation and param.annotation is not param.empty:
arg.write(' = ')
Expand All @@ -791,7 +794,7 @@ def stringify_signature(sig: inspect.Signature, show_annotation: bool = True,
show_return_annotation is False):
return '(%s)' % ', '.join(args)
else:
annotation = stringify_annotation(sig.return_annotation)
annotation = stringify_annotation(sig.return_annotation, unqualified_typehints)
return '(%s) -> %s' % (', '.join(args), annotation)


Expand Down
4 changes: 4 additions & 0 deletions tests/test_util_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,10 @@ def test_signature_annotations():
sig = inspect.signature(f7)
assert stringify_signature(sig, show_return_annotation=False) == '(x: Optional[int] = None, y: dict = {})'

# unqualified_typehints is True
sig = inspect.signature(f7)
assert stringify_signature(sig, unqualified_typehints=True) == '(x: ~typing.Optional[int] = None, y: dict = {}) -> None'


@pytest.mark.skipif(sys.version_info < (3, 8), reason='python 3.8+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
Expand Down

0 comments on commit 5aa6cbb

Please sign in to comment.