Skip to content

Commit 9eb3d79

Browse files
authored
Add a shared utilities module for autodoc (#14037)
1 parent 245dea0 commit 9eb3d79

File tree

16 files changed

+228
-149
lines changed

16 files changed

+228
-149
lines changed

sphinx/ext/autodoc/_docstrings.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525

2626
from sphinx.events import EventManager
2727
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions
28-
from sphinx.ext.autodoc._importer import _AttrGetter
2928
from sphinx.ext.autodoc._property_types import _ItemProperties
29+
from sphinx.ext.autodoc._shared import _AttrGetter
3030

3131
logger = logging.getLogger('sphinx.ext.autodoc')
3232

sphinx/ext/autodoc/_generate.py

Lines changed: 13 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from sphinx.ext.autodoc._member_finder import _gather_members
1010
from sphinx.ext.autodoc._renderer import _add_content, _directive_header_lines
1111
from sphinx.ext.autodoc._sentinels import ALL
12+
from sphinx.ext.autodoc._shared import _get_render_mode
1213
from sphinx.ext.autodoc.mock import ismock
1314
from sphinx.locale import _, __
1415
from sphinx.pycode import ModuleAnalyzer
@@ -17,14 +18,12 @@
1718

1819
if TYPE_CHECKING:
1920
from collections.abc import Iterator, Mapping, MutableSet
20-
from typing import Literal
2121

22-
from sphinx.config import Config
2322
from sphinx.environment import _CurrentDocument
2423
from sphinx.events import EventManager
2524
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions
26-
from sphinx.ext.autodoc._importer import _AttrGetter
2725
from sphinx.ext.autodoc._property_types import _ItemProperties
26+
from sphinx.ext.autodoc._shared import _AttrGetter, _AutodocConfig
2827
from sphinx.util.typing import _RestifyMode
2928

3029
logger = logging.getLogger('sphinx.ext.autodoc')
@@ -36,7 +35,7 @@ def _generate_directives(
3635
check_module: bool = False,
3736
all_members: bool = False,
3837
*,
39-
config: Config,
38+
config: _AutodocConfig,
4039
current_document: _CurrentDocument,
4140
events: EventManager,
4241
get_attr: _AttrGetter,
@@ -154,7 +153,7 @@ def _add_directive_lines(
154153
*,
155154
more_content: StringList | None,
156155
is_final: bool,
157-
config: Config,
156+
config: _AutodocConfig,
158157
indent: str,
159158
options: _AutoDocumenterOptions,
160159
props: _ItemProperties,
@@ -180,8 +179,8 @@ def _add_directive_lines(
180179

181180
# add alias information, if applicable
182181
lines = _body_alias_lines(
183-
typehints_format=config.autodoc_typehints_format,
184-
python_display_short_literal_types=config.python_display_short_literal_types,
182+
render_mode=_get_render_mode(config.autodoc_typehints_format),
183+
short_literals=config.python_display_short_literal_types,
185184
props=props,
186185
)
187186
alias_lines = StringList(list(lines), source='')
@@ -204,7 +203,7 @@ def _document_members(
204203
all_members: bool,
205204
analyzer_order: dict[str, int],
206205
attr_docs: dict[tuple[str, str], list[str]],
207-
config: Config,
206+
config: _AutodocConfig,
208207
current_document: _CurrentDocument,
209208
events: EventManager,
210209
get_attr: _AttrGetter,
@@ -276,22 +275,17 @@ def _document_members(
276275

277276

278277
def _body_alias_lines(
279-
*,
280-
props: _ItemProperties,
281-
typehints_format: Literal['fully-qualified', 'short'],
282-
python_display_short_literal_types: bool,
278+
*, props: _ItemProperties, render_mode: _RestifyMode, short_literals: bool
283279
) -> Iterator[str]:
284280
"""Add content from docstrings, attribute documentation and user."""
285281
if props.obj_type in {'data', 'attribute'}:
286282
from sphinx.ext.autodoc._property_types import _AssignStatementProperties
287283

288284
assert isinstance(props, _AssignStatementProperties)
289285

290-
mode = _get_render_mode(typehints_format)
291-
292286
# Support for documenting GenericAliases
293287
if props._obj_is_generic_alias:
294-
alias = restify(props._obj, mode=mode)
288+
alias = restify(props._obj, mode=render_mode)
295289
yield _('alias of %s') % alias
296290
yield ''
297291
return
@@ -303,27 +297,25 @@ def _body_alias_lines(
303297
assert isinstance(props, _ClassDefProperties)
304298

305299
obj = props._obj
306-
mode = _get_render_mode(typehints_format)
307300

308301
if props._obj_is_new_type:
309-
supertype = restify(obj.__supertype__, mode=mode)
302+
supertype = restify(obj.__supertype__, mode=render_mode)
310303
yield _('alias of %s') % supertype
311304
yield ''
312305
return
313306

314307
if props._obj_is_typevar:
315-
short_literals = python_display_short_literal_types
316308
attrs = [
317309
repr(obj.__name__),
318310
*(
319311
stringify_annotation(
320-
constraint, mode, short_literals=short_literals
312+
constraint, render_mode, short_literals=short_literals
321313
)
322314
for constraint in obj.__constraints__
323315
),
324316
]
325317
if obj.__bound__:
326-
attrs.append(rf'bound=\ {restify(obj.__bound__, mode=mode)}')
318+
attrs.append(rf'bound=\ {restify(obj.__bound__, mode=render_mode)}')
327319
if obj.__covariant__:
328320
attrs.append('covariant=True')
329321
if obj.__contravariant__:
@@ -345,7 +337,7 @@ def _body_alias_lines(
345337

346338
if class_var_doc_comment:
347339
return
348-
alias = restify(obj, mode=mode)
340+
alias = restify(obj, mode=render_mode)
349341
yield _('alias of %s') % alias
350342
return
351343

@@ -367,11 +359,3 @@ def _docstring_source_name(*, props: _ItemProperties, source: str) -> str:
367359
if source:
368360
return f'{source}:docstring of {fullname}'
369361
return f'docstring of {fullname}'
370-
371-
372-
def _get_render_mode(
373-
typehints_format: Literal['fully-qualified', 'short'],
374-
) -> _RestifyMode:
375-
if typehints_format == 'short':
376-
return 'smart'
377-
return 'fully-qualified-except-typing'

sphinx/ext/autodoc/_importer.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from sphinx.util.typing import get_type_hints
2424

2525
if TYPE_CHECKING:
26-
from collections.abc import Sequence
26+
from collections.abc import Mapping, Sequence
2727
from importlib.machinery import ModuleSpec
2828
from types import ModuleType
2929
from typing import Any, Protocol
@@ -71,11 +71,11 @@ def __repr__(self) -> str:
7171
def _import_object(
7272
*,
7373
get_attr: _AttrGetter = safe_getattr,
74-
mock_imports: list[str],
74+
mock_imports: Sequence[str],
7575
module_name: str,
7676
obj_path: Sequence[str],
7777
obj_type: _AutodocObjType,
78-
type_aliases: dict[str, Any] | None,
78+
type_aliases: Mapping[str, str] | None,
7979
) -> _ImportedObject | None:
8080
"""Import the module and get the object to document."""
8181
try:
@@ -310,8 +310,8 @@ def _import_data_declaration(
310310
*,
311311
module_name: str,
312312
obj_path: Sequence[str],
313-
mock_imports: list[str],
314-
type_aliases: dict[str, Any] | None,
313+
mock_imports: Sequence[str],
314+
type_aliases: Mapping[str, str] | None,
315315
) -> _ImportedObject | None:
316316
# annotation only instance variable (PEP-526)
317317
try:
@@ -333,8 +333,8 @@ def _import_attribute_declaration(
333333
*,
334334
module_name: str,
335335
obj_path: Sequence[str],
336-
mock_imports: list[str],
337-
type_aliases: dict[str, Any] | None,
336+
mock_imports: Sequence[str],
337+
type_aliases: Mapping[str, str] | None,
338338
get_attr: _AttrGetter = safe_getattr,
339339
) -> _ImportedObject | None:
340340
# Support runtime & uninitialized instance attributes.
@@ -424,7 +424,7 @@ def _get_attribute_comment(
424424

425425

426426
def _is_uninitialized_instance_attribute(
427-
*, parent: Any, obj_path: Sequence[str], type_aliases: dict[str, Any] | None
427+
*, parent: Any, obj_path: Sequence[str], type_aliases: Mapping[str, str] | None
428428
) -> bool:
429429
"""Check the subject is an annotation only attribute."""
430430
annotations = get_type_hints(parent, None, type_aliases, include_extras=True)

sphinx/ext/autodoc/_loader.py

Lines changed: 13 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
SLOTS_ATTR,
2828
UNINITIALIZED_ATTR,
2929
)
30+
from sphinx.ext.autodoc._shared import _get_render_mode
3031
from sphinx.ext.autodoc._signatures import _format_signatures
3132
from sphinx.ext.autodoc._type_comments import (
3233
_ensure_annotations_from_type_comments,
@@ -42,12 +43,12 @@
4243
from collections.abc import Mapping, MutableSet, Sequence
4344
from typing import Any
4445

45-
from sphinx.config import Config
4646
from sphinx.environment import _CurrentDocument
4747
from sphinx.events import EventManager
4848
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions
49-
from sphinx.ext.autodoc._importer import _AttrGetter, _ImportedObject
49+
from sphinx.ext.autodoc._importer import _ImportedObject
5050
from sphinx.ext.autodoc._property_types import _AutodocFuncProperty, _AutodocObjType
51+
from sphinx.ext.autodoc._shared import _AttrGetter, _AutodocConfig
5152

5253
logger = logging.getLogger(__name__)
5354

@@ -58,10 +59,8 @@ def _load_object_by_name(
5859
*,
5960
name: str,
6061
objtype: _AutodocObjType,
61-
mock_imports: list[str],
62-
type_aliases: dict[str, Any] | None,
6362
current_document: _CurrentDocument,
64-
config: Config,
63+
config: _AutodocConfig,
6564
events: EventManager,
6665
get_attr: _AttrGetter,
6766
options: _AutoDocumenterOptions,
@@ -84,10 +83,10 @@ def _load_object_by_name(
8483
im = _import_object(
8584
module_name=module_name,
8685
obj_path=parts,
87-
mock_imports=mock_imports,
86+
mock_imports=config.autodoc_mock_imports,
8887
get_attr=get_attr,
8988
obj_type=objtype,
90-
type_aliases=type_aliases,
89+
type_aliases=config.autodoc_type_aliases,
9190
)
9291
if im is None:
9392
# See BuildEnvironment.note_reread()
@@ -164,7 +163,7 @@ def _load_object_by_name(
164163
def _make_props_from_imported_object(
165164
im: _ImportedObject,
166165
*,
167-
config: Config,
166+
config: _AutodocConfig,
168167
events: EventManager,
169168
get_attr: _AttrGetter,
170169
module_name: str,
@@ -175,6 +174,7 @@ def _make_props_from_imported_object(
175174
object_name = im.object_name
176175
obj = im.obj
177176
obj_properties: set[_AutodocFuncProperty] = set()
177+
render_mode = _get_render_mode(config.autodoc_typehints_format)
178178

179179
if objtype == 'module':
180180
try:
@@ -232,11 +232,7 @@ def _make_props_from_imported_object(
232232
SimpleNamespace(),
233233
obj_bases,
234234
)
235-
if config.autodoc_typehints_format == 'short':
236-
mode = 'smart'
237-
else:
238-
mode = 'fully-qualified-except-typing'
239-
base_classes = tuple(restify(cls, mode=mode) for cls in obj_bases) # type: ignore[arg-type]
235+
base_classes = tuple(restify(cls, mode=render_mode) for cls in obj_bases)
240236

241237
return _ClassDefProperties(
242238
obj_type=objtype, # type: ignore[arg-type]
@@ -342,15 +338,11 @@ def _make_props_from_imported_object(
342338
except ValueError:
343339
pass
344340
else:
345-
if config.autodoc_typehints_format == 'short':
346-
mode = 'smart'
347-
else:
348-
mode = 'fully-qualified-except-typing'
349341
if signature.return_annotation is not Parameter.empty:
350342
short_literals = config.python_display_short_literal_types
351343
obj_property_type_annotation = stringify_annotation(
352344
signature.return_annotation,
353-
mode, # type: ignore[arg-type]
345+
render_mode,
354346
short_literals=short_literals,
355347
)
356348

@@ -378,16 +370,10 @@ def _make_props_from_imported_object(
378370
config.autodoc_type_aliases,
379371
include_extras=True,
380372
)
381-
if config.autodoc_typehints_format == 'short':
382-
mode = 'smart'
383-
else:
384-
mode = 'fully-qualified-except-typing'
385373
if parts[-1] in annotations:
386374
short_literals = config.python_display_short_literal_types
387375
type_annotation = stringify_annotation(
388-
annotations[parts[-1]],
389-
mode, # type: ignore[arg-type]
390-
short_literals=short_literals,
376+
annotations[parts[-1]], render_mode, short_literals=short_literals
391377
)
392378
else:
393379
type_annotation = None
@@ -436,16 +422,10 @@ def _make_props_from_imported_object(
436422
config.autodoc_type_aliases,
437423
include_extras=True,
438424
)
439-
if config.autodoc_typehints_format == 'short':
440-
mode = 'smart'
441-
else:
442-
mode = 'fully-qualified-except-typing'
443425
if parts[-1] in annotations:
444426
short_literals = config.python_display_short_literal_types
445427
type_annotation = stringify_annotation(
446-
annotations[parts[-1]],
447-
mode, # type: ignore[arg-type]
448-
short_literals=short_literals,
428+
annotations[parts[-1]], render_mode, short_literals=short_literals
449429
)
450430
else:
451431
type_annotation = None
@@ -485,15 +465,9 @@ def _make_props_from_imported_object(
485465
parts = tuple(bases) + parts
486466
module_name = obj_module_name
487467

488-
if config.autodoc_typehints_format == 'short':
489-
mode = 'smart'
490-
else:
491-
mode = 'fully-qualified-except-typing'
492468
short_literals = config.python_display_short_literal_types
493469
ann = stringify_annotation(
494-
obj.__value__,
495-
mode, # type: ignore[arg-type]
496-
short_literals=short_literals,
470+
obj.__value__, render_mode, short_literals=short_literals
497471
)
498472
return _TypeStatementProperties(
499473
obj_type=objtype,

sphinx/ext/autodoc/_member_finder.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,17 @@
3232
from collections.abc import Iterable, Iterator, Mapping, MutableSet, Sequence, Set
3333
from typing import Any, Literal
3434

35-
from sphinx.config import Config
3635
from sphinx.environment import _CurrentDocument
3736
from sphinx.events import EventManager
3837
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions
39-
from sphinx.ext.autodoc._importer import _AttrGetter
4038
from sphinx.ext.autodoc._property_types import _AutodocObjType, _ItemProperties
4139
from sphinx.ext.autodoc._sentinels import (
4240
ALL_T,
4341
EMPTY_T,
4442
INSTANCE_ATTR_T,
4543
SLOTS_ATTR_T,
4644
)
45+
from sphinx.ext.autodoc._shared import _AttrGetter, _AutodocConfig
4746

4847
logger = logging.getLogger('sphinx.ext.autodoc')
4948
special_member_re = re.compile(r'^__\S+__$')
@@ -94,7 +93,7 @@ def _gather_members(
9493
indent: str,
9594
analyzer_order: dict[str, int],
9695
attr_docs: dict[tuple[str, str], list[str]],
97-
config: Config,
96+
config: _AutodocConfig,
9897
current_document: _CurrentDocument,
9998
events: EventManager,
10099
get_attr: _AttrGetter,
@@ -176,8 +175,6 @@ def _gather_members(
176175
member_props = _load_object_by_name(
177176
name=full_name,
178177
objtype=obj_type,
179-
mock_imports=config.autodoc_mock_imports,
180-
type_aliases=config.autodoc_type_aliases,
181178
current_document=current_document,
182179
config=config,
183180
events=events,

0 commit comments

Comments
 (0)