Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
07746bc
updates CHANGES
picnixz Feb 24, 2024
31877b0
fix :confval:`python_display_short_literal_types`
picnixz Feb 24, 2024
92eb945
add tests
picnixz Feb 24, 2024
dbd4628
Fix lint.
picnixz Feb 24, 2024
bf84060
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Feb 29, 2024
4d73d55
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 2, 2024
bd17e8c
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 23, 2024
93f822a
Update CHANGES.rst
picnixz Mar 23, 2024
dc61297
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 23, 2024
5ab3b87
Update __init__.py
picnixz Mar 23, 2024
5cc3657
Update inspect.py
picnixz Mar 23, 2024
032bf8c
Update sphinx/util/typing.py
picnixz Mar 23, 2024
67f1219
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 23, 2024
987af4c
Merge remote-tracking branch 'upstream/master' into fix/11995-python-…
picnixz Mar 27, 2024
8c6f1ed
revert some format
picnixz Mar 27, 2024
ae4145e
revert some format
picnixz Mar 27, 2024
2089d29
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 27, 2024
1228326
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Mar 28, 2024
6b8fad3
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 1, 2024
70a70ca
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 4, 2024
13cf2c0
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 4, 2024
c035957
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 4, 2024
28d4733
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 5, 2024
eebfdd4
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 12, 2024
92b129b
Merge remote-tracking branch 'upstream/master' into fix/11995-python-…
picnixz Apr 24, 2024
deed23c
fixup!
picnixz Apr 24, 2024
00632e5
revert some mistake
picnixz Apr 24, 2024
d72aefc
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 24, 2024
cb1c317
fixup
picnixz Apr 24, 2024
0b6f61a
fixup
picnixz Apr 24, 2024
f91b1c4
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 25, 2024
c4731c7
cleanup
picnixz Apr 25, 2024
9e0bdc0
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz Apr 27, 2024
f134286
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz May 1, 2024
7dcbe64
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz May 21, 2024
d7f0508
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz May 22, 2024
d0bde20
Merge branch 'master' into fix/11995-python-display-short-literal
picnixz May 28, 2024
ad1c4a5
Merge remote-tracking branch 'upstream/master' into fix/11995-python-…
picnixz Jul 20, 2024
520363f
update CHANGES & fixup
picnixz Jul 20, 2024
81d928f
Merge branch 'master' into fix/11995-python-display-short-literal
AA-Turner Feb 2, 2025
327011f
post-merge
AA-Turner Feb 2, 2025
04bc826
Drop _Mode
AA-Turner Feb 2, 2025
bb6a019
Remove all RenderMode enum changes
AA-Turner Feb 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ Features added
* #8191, #8159: Add :rst:dir:`inheritance-diagram:include-subclasses` option to
the :rst:dir:`inheritance-diagram` directive.
Patch by Walter Dörwald.
* #11995: autodoc: Add support for :confval:`python_display_short_literal_types`.
Patch by Bénédikt Tran and Adam Turner.

Bugs fixed
----------
Expand Down
104 changes: 54 additions & 50 deletions sphinx/ext/autodoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
from sphinx.environment import BuildEnvironment, _CurrentDocument
from sphinx.events import EventManager
from sphinx.ext.autodoc.directive import DocumenterBridge
from sphinx.util.typing import ExtensionMetadata, OptionSpec
from sphinx.util.typing import ExtensionMetadata, OptionSpec, _RestifyMode

_AutodocObjType = Literal[
'module', 'class', 'exception', 'function', 'method', 'attribute'
Expand Down Expand Up @@ -76,6 +76,14 @@
special_member_re = re.compile(r'^__\S+__$')


def _get_render_mode(
typehints_format: Literal['fully-qualified', 'short'],
) -> _RestifyMode:
if typehints_format == 'short':
return 'smart'
return 'fully-qualified-except-typing'


def identity(x: Any) -> Any:
return x

Expand Down Expand Up @@ -1472,6 +1480,8 @@ def format_args(self, **kwargs: Any) -> str:
kwargs.setdefault('show_annotation', False)
if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

try:
self._events.emit('autodoc-before-process-signature', self.object, False)
Expand Down Expand Up @@ -1507,6 +1517,8 @@ def add_directive_header(self, sig: str) -> None:
def format_signature(self, **kwargs: Any) -> str:
if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

sigs = []
if (
Expand Down Expand Up @@ -1794,6 +1806,8 @@ def format_args(self, **kwargs: Any) -> str:
kwargs.setdefault('show_annotation', False)
if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

try:
self._signature_class, _signature_method_name, sig = self._get_signature()
Expand Down Expand Up @@ -1835,6 +1849,8 @@ def format_signature(self, **kwargs: Any) -> str:

if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

sig = super().format_signature()
sigs = []
Expand Down Expand Up @@ -1931,10 +1947,8 @@ def add_directive_header(self, sig: str) -> None:
'autodoc-process-bases', self.fullname, self.object, self.options, bases
)

if self.config.autodoc_typehints_format == 'short':
base_classes = [restify(cls, 'smart') for cls in bases]
else:
base_classes = [restify(cls) for cls in bases]
mode = _get_render_mode(self.config.autodoc_typehints_format)
base_classes = [restify(cls, mode=mode) for cls in bases]

sourcename = self.get_sourcename()
self.add_line('', sourcename)
Expand Down Expand Up @@ -2047,25 +2061,21 @@ def get_variable_comment(self) -> list[str] | None:
return None

def add_content(self, more_content: StringList | None) -> None:
mode = _get_render_mode(self.config.autodoc_typehints_format)
short_literals = self.config.python_display_short_literal_types

if isinstance(self.object, NewType):
if self.config.autodoc_typehints_format == 'short':
supertype = restify(self.object.__supertype__, 'smart')
else:
supertype = restify(self.object.__supertype__)
supertype = restify(self.object.__supertype__, mode=mode)

more_content = StringList([_('alias of %s') % supertype, ''], source='')
if isinstance(self.object, TypeVar):
attrs = [repr(self.object.__name__)]
for constraint in self.object.__constraints__:
if self.config.autodoc_typehints_format == 'short':
attrs.append(stringify_annotation(constraint, 'smart'))
else:
attrs.append(stringify_annotation(constraint))
attrs.extend(
stringify_annotation(constraint, mode, short_literals=short_literals)
for constraint in self.object.__constraints__
)
if self.object.__bound__:
if self.config.autodoc_typehints_format == 'short':
bound = restify(self.object.__bound__, 'smart')
else:
bound = restify(self.object.__bound__)
bound = restify(self.object.__bound__, mode=mode)
attrs.append(r'bound=\ ' + bound)
if self.object.__covariant__:
attrs.append('covariant=True')
Expand All @@ -2085,10 +2095,7 @@ def add_content(self, more_content: StringList | None) -> None:

if self.doc_as_attr and not self.get_variable_comment():
try:
if self.config.autodoc_typehints_format == 'short':
alias = restify(self.object, 'smart')
else:
alias = restify(self.object)
alias = restify(self.object, mode=mode)
more_content = StringList([_('alias of %s') % alias], source='')
except AttributeError:
pass # Invalid class object is passed.
Expand Down Expand Up @@ -2180,10 +2187,8 @@ def should_suppress_directive_header(self) -> bool:

def update_content(self, more_content: StringList) -> None:
if inspect.isgenericalias(self.object):
if self.config.autodoc_typehints_format == 'short':
alias = restify(self.object, 'smart')
else:
alias = restify(self.object)
mode = _get_render_mode(self.config.autodoc_typehints_format)
alias = restify(self.object, mode=mode)

more_content.append(_('alias of %s') % alias, '')
more_content.append('', '')
Expand Down Expand Up @@ -2307,15 +2312,13 @@ def add_directive_header(self, sig: str) -> None:
include_extras=True,
)
if self.objpath[-1] in annotations:
if self.config.autodoc_typehints_format == 'short':
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]), 'smart'
)
else:
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]),
'fully-qualified-except-typing',
)
mode = _get_render_mode(self.config.autodoc_typehints_format)
short_literals = self.config.python_display_short_literal_types
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]),
mode,
short_literals=short_literals,
)
self.add_line(' :type: ' + objrepr, sourcename)

try:
Expand Down Expand Up @@ -2405,6 +2408,8 @@ def format_args(self, **kwargs: Any) -> str:
kwargs.setdefault('show_annotation', False)
if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

try:
if self.object == object.__init__ and self.parent != object: # NoQA: E721
Expand Down Expand Up @@ -2474,6 +2479,8 @@ def document_members(self, all_members: bool = False) -> None:
def format_signature(self, **kwargs: Any) -> str:
if self.config.autodoc_typehints_format == 'short':
kwargs.setdefault('unqualified_typehints', True)
if self.config.python_display_short_literal_types:
kwargs.setdefault('short_literals', True)

sigs = []
if (
Expand Down Expand Up @@ -2957,15 +2964,13 @@ def add_directive_header(self, sig: str) -> None:
include_extras=True,
)
if self.objpath[-1] in annotations:
if self.config.autodoc_typehints_format == 'short':
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]), 'smart'
)
else:
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]),
'fully-qualified-except-typing',
)
mode = _get_render_mode(self.config.autodoc_typehints_format)
short_literals = self.config.python_display_short_literal_types
objrepr = stringify_annotation(
annotations.get(self.objpath[-1]),
mode,
short_literals=short_literals,
)
self.add_line(' :type: ' + objrepr, sourcename)

try:
Expand Down Expand Up @@ -3100,12 +3105,11 @@ def add_directive_header(self, sig: str) -> None:
func, type_aliases=self.config.autodoc_type_aliases
)
if signature.return_annotation is not Parameter.empty:
if self.config.autodoc_typehints_format == 'short':
objrepr = stringify_annotation(signature.return_annotation, 'smart')
else:
objrepr = stringify_annotation(
signature.return_annotation, 'fully-qualified-except-typing'
)
mode = _get_render_mode(self.config.autodoc_typehints_format)
short_literals = self.config.python_display_short_literal_types
objrepr = stringify_annotation(
signature.return_annotation, mode, short_literals=short_literals
)
self.add_line(' :type: ' + objrepr, sourcename)
except TypeError as exc:
logger.warning(
Expand Down
12 changes: 8 additions & 4 deletions sphinx/ext/autodoc/typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from sphinx.application import Sphinx
from sphinx.ext.autodoc import Options
from sphinx.util.typing import ExtensionMetadata
from sphinx.util.typing import ExtensionMetadata, _StringifyMode


def record_typehints(
Expand All @@ -33,11 +33,14 @@ def record_typehints(
retann: str,
) -> None:
"""Record type hints to env object."""
mode: _StringifyMode
if app.config.autodoc_typehints_format == 'short':
mode = 'smart'
else:
mode = 'fully-qualified'

short_literals = app.config.python_display_short_literal_types

try:
if callable(obj):
current_document = app.env.current_document
Expand All @@ -46,11 +49,12 @@ def record_typehints(
for param in sig.parameters.values():
if param.annotation is not param.empty:
annotation[param.name] = stringify_annotation(
param.annotation,
mode, # type: ignore[arg-type]
param.annotation, mode, short_literals=short_literals
)
if sig.return_annotation is not sig.empty:
annotation['return'] = stringify_annotation(sig.return_annotation, mode) # type: ignore[arg-type]
annotation['return'] = stringify_annotation(
sig.return_annotation, mode, short_literals=short_literals
)
except (TypeError, ValueError):
pass

Expand Down
7 changes: 6 additions & 1 deletion sphinx/ext/napoleon/docstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,8 +1095,13 @@ def _lookup_annotation(self, _name: str) -> str:
)
self._annotations = get_type_hints(self._obj, None, localns)
if _name in self._annotations:
short_literals = getattr(
self._config, 'python_display_short_literal_types', False
)
return stringify_annotation(
self._annotations[_name], 'fully-qualified-except-typing'
self._annotations[_name],
mode='fully-qualified-except-typing',
short_literals=short_literals,
)
# No annotation found
return ''
Expand Down
15 changes: 13 additions & 2 deletions sphinx/util/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

from typing_extensions import TypeIs

from sphinx.util.typing import _StringifyMode

class _SupportsGet(Protocol):
def __get__(self, instance: Any, owner: type | None = ..., /) -> Any: ...

Expand Down Expand Up @@ -842,14 +844,17 @@ def stringify_signature(
show_annotation: bool = True,
show_return_annotation: bool = True,
unqualified_typehints: bool = False,
short_literals: bool = False,
) -> str:
"""Stringify a :class:`~inspect.Signature` object.

:param show_annotation: If enabled, show annotations on the signature
:param show_return_annotation: If enabled, show annotation of the return value
:param unqualified_typehints: If enabled, show annotations as unqualified
(ex. io.StringIO -> StringIO)
:param short_literals: If enabled, use short literal types.
"""
mode: _StringifyMode
if unqualified_typehints:
mode = 'smart'
else:
Expand Down Expand Up @@ -884,7 +889,11 @@ def stringify_signature(

if show_annotation and param.annotation is not EMPTY:
arg.write(': ')
arg.write(stringify_annotation(param.annotation, mode)) # type: ignore[arg-type]
arg.write(
stringify_annotation(
param.annotation, mode, short_literals=short_literals
)
)
if param.default is not EMPTY:
if show_annotation and param.annotation is not EMPTY:
arg.write(' = ')
Expand All @@ -907,7 +916,9 @@ def stringify_signature(
):
return f'({concatenated_args})'
else:
retann = stringify_annotation(sig.return_annotation, mode) # type: ignore[arg-type]
retann = stringify_annotation(
sig.return_annotation, mode, short_literals=short_literals
)
return f'({concatenated_args}) -> {retann}'


Expand Down
Loading