| 1 |
"""Sphinx extension that defines new auto documenters with autosummary. |
| 2 |
|
| 3 |
The :class:`AutoSummModuleDocumenter` and :class:`AutoSummClassDocumenter` |
| 4 |
classes defined here enable an autosummary-style listing of the corresponding |
| 5 |
members. |
| 6 |
|
| 7 |
This extension gives also the possibility to choose which data shall be shown |
| 8 |
and to include the docstring of the ``'__call__'`` attribute. |
| 9 |
|
| 10 |
**Disclaimer** |
| 11 |
|
| 12 |
Copyright 2016-2019, Philipp S. Sommer |
| 13 |
|
| 14 |
Copyright 2020-2021, Helmholtz-Zentrum Hereon |
| 15 |
|
| 16 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 17 |
you may not use this file except in compliance with the License. |
| 18 |
You may obtain a copy of the License at |
| 19 |
|
| 20 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 21 |
|
| 22 |
Unless required by applicable law or agreed to in writing, software |
| 23 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 24 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 25 |
See the License for the specific language governing permissions and |
| 26 |
limitations under the License. |
| 27 |
""" |
| 28 |
|
| 29 |
__author__ = "Philipp S. Sommer" |
| 30 |
__copyright__ = ( |
| 31 |
"2016 - 2019, Philipp S. Sommer\n" |
| 32 |
"2020 - 2021, Helmholtz-Zentrum Hereon" |
| 33 |
) |
| 34 |
__credits__ = ["Philipp S. Sommer"] |
| 35 |
__license__ = "Apache-2.0" |
| 36 |
|
| 37 |
__maintainer__ = "Philipp S. Sommer" |
| 38 |
__email__ = "[email protected]" |
| 39 |
|
| 40 |
__status__ = "Production" |
| 41 |
|
| 42 |
from itertools import chain |
| 43 |
from typing import TYPE_CHECKING |
| 44 |
|
| 45 |
from sphinx.util import logging |
| 46 |
import re |
| 47 |
|
| 48 |
from docutils import nodes |
| 49 |
|
| 50 |
import sphinx |
| 51 |
|
| 52 |
from sphinx.util.docutils import SphinxDirective |
| 53 |
|
| 54 |
from sphinx.ext.autodoc import ( |
| 55 |
ClassDocumenter, ModuleDocumenter, ALL, PycodeError, |
| 56 |
ModuleAnalyzer, AttributeDocumenter, DataDocumenter, Options, ExceptionDocumenter, |
| 57 |
Documenter, prepare_docstring) |
| 58 |
import sphinx.ext.autodoc as ad |
| 59 |
|
| 60 |
signature = Signature = None |
| 61 |
|
| 62 |
from sphinx.ext.autodoc.directive import ( |
| 63 |
AutodocDirective, AUTODOC_DEFAULT_OPTIONS, process_documenter_options, |
| 64 |
DocumenterBridge |
| 65 |
) |
| 66 |
|
| 67 |
try: |
| 68 |
from sphinx.util.inspect import signature, stringify_signature |
| 69 |
except ImportError: |
| 70 |
from sphinx.ext.autodoc import Signature |
| 71 |
|
| 72 |
sphinx_version = list(map(float, re.findall(r'\d+', sphinx.__version__)[:3])) |
| 73 |
|
| 74 |
try: |
| 75 |
from sphinx.util import force_decode |
| 76 |
except ImportError: |
| 77 |
# force_decode has been removed with sphinx 4.0 |
| 78 |
def force_decode(string: str, encoding: str) -> str: |
| 79 |
return string |
| 80 |
|
| 81 |
|
| 82 |
from . import _version |
| 83 |
__version__ = _version.get_versions()['version'] |
| 84 |
|
| 85 |
|
| 86 |
if TYPE_CHECKING: # pragma: no cover |
| 87 |
DOCUMENTER_MIXIN_BASE = Documenter |
| 88 |
else: |
| 89 |
DOCUMENTER_MIXIN_BASE = object |
| 90 |
|
| 91 |
|
| 92 |
logger = logging.getLogger(__name__) |
| 93 |
|
| 94 |
#: Options of the :class:`sphinx.ext.autodoc.ModuleDocumenter` that have an |
| 95 |
#: effect on the selection of members for the documentation |
| 96 |
member_options = { |
| 97 |
'members', 'undoc-members', 'inherited-members', 'exclude-members', |
| 98 |
'private-members', 'special-members', 'imported-members', |
| 99 |
'ignore-module-all'} |
| 100 |
|
| 101 |
|
| 102 |
if signature is not None: # sphinx >= 2.4.0 |
| 103 |
def process_signature(obj): |
| 104 |
sig = signature(obj) |
| 105 |
return stringify_signature(sig) |
| 106 |
elif Signature is not None: # sphinx >= 1.7 |
| 107 |
def process_signature(obj): |
| 108 |
try: |
| 109 |
args = Signature(obj).format_args() |
| 110 |
except TypeError: |
| 111 |
return None |
| 112 |
else: |
| 113 |
args = args.replace('\\', '\\\\') |
| 114 |
return args |
| 115 |
|
| 116 |
|
| 117 |
def list_option(option): |
| 118 |
"""Transform a string to a list by splitting at ;;.""" |
| 119 |
return [s.strip() for s in option.split(";;")] |
| 120 |
|
| 121 |
|
| 122 |
def bool_option(*args): |
| 123 |
return "True" |
| 124 |
|
| 125 |
|
| 126 |
def _get_arg(param, pos, default, *args, **kwargs): |
| 127 |
if param in kwargs: |
| 128 |
return kwargs[param] |
| 129 |
elif len(args) > pos: |
| 130 |
return args[pos] |
| 131 |
else: |
| 132 |
return default |
| 133 |
|
| 134 |
|
| 135 |
class AutosummaryDocumenter(DOCUMENTER_MIXIN_BASE): |
| 136 |
"""Abstract class for for extending Documenter methods |
| 137 |
|
| 138 |
This classed is used as a base class for Documenters in order to provide |
| 139 |
the necessary methods for generating the autosummary.""" |
| 140 |
|
| 141 |
#: List of functions that may filter the members |
| 142 |
filter_funcs = [] |
| 143 |
|
| 144 |
#: Grouper functions |
| 145 |
grouper_funcs = [] |
| 146 |
|
| 147 |
member_sections: dict |
| 148 |
|
| 149 |
def __init__(self): |
| 150 |
raise NotImplementedError |
| 151 |
|
| 152 |
def get_grouped_documenters(self, all_members=False): |
| 153 |
"""Method to return the member documenters |
| 154 |
|
| 155 |
This method is somewhat like a combination of the |
| 156 |
:meth:`sphinx.ext.autodoc.ModuleDocumenter.generate` method and the |
| 157 |
:meth:`sphinx.ext.autodoc.ModuleDocumenter.document_members` method. |
| 158 |
Hence it initializes this instance by importing the object, etc. and |
| 159 |
it finds the documenters to use for the autosummary option in the same |
| 160 |
style as the document_members does it. |
| 161 |
|
| 162 |
Returns |
| 163 |
------- |
| 164 |
dict |
| 165 |
dictionary whose keys are determined by the :attr:`member_sections` |
| 166 |
dictionary and whose values are lists of tuples. Each tuple |
| 167 |
consists of a documenter and a boolean to identify whether a module |
| 168 |
check should be made describes an attribute or not. |
| 169 |
|
| 170 |
Notes |
| 171 |
----- |
| 172 |
If a :class:`sphinx.ext.autodoc.Documenter.member_order` value is not |
| 173 |
in the :attr:`member_sections` dictionary, it will be put into an |
| 174 |
additional `Miscellaneous` section.""" |
| 175 |
use_sections = self.options.autosummary_sections |
| 176 |
|
| 177 |
self.parse_name() |
| 178 |
self.import_object() |
| 179 |
# If there is no real module defined, figure out which to use. |
| 180 |
# The real module is used in the module analyzer to look up the module |
| 181 |
# where the attribute documentation would actually be found in. |
| 182 |
# This is used for situations where you have a module that collects the |
| 183 |
# functions and classes of internal submodules. |
| 184 |
self.real_modname = None or self.get_real_modname() |
| 185 |
|
| 186 |
# try to also get a source code analyzer for attribute docs |
| 187 |
if sphinx_version < [4, 0]: |
| 188 |
record_dependencies = self.directive.filename_set |
| 189 |
else: |
| 190 |
record_dependencies = self.directive.record_dependencies |
| 191 |
try: |
| 192 |
self.analyzer = ModuleAnalyzer.for_module(self.real_modname) |
| 193 |
# parse right now, to get PycodeErrors on parsing (results will |
| 194 |
# be cached anyway) |
| 195 |
self.analyzer.find_attr_docs() |
| 196 |
except PycodeError as err: |
| 197 |
logger.debug('[autodocsumm] module analyzer failed: %s', err) |
| 198 |
# no source file -- e.g. for builtin and C modules |
| 199 |
self.analyzer = None |
| 200 |
# at least add the module.__file__ as a dependency |
| 201 |
if hasattr(self.module, '__file__') and self.module.__file__: |
| 202 |
record_dependencies.add(self.module.__file__) |
| 203 |
else: |
| 204 |
record_dependencies.add(self.analyzer.srcname) |
| 205 |
|
| 206 |
self.env.temp_data['autodoc:module'] = self.modname |
| 207 |
if self.objpath: |
| 208 |
self.env.temp_data['autodoc:class'] = self.objpath[0] |
| 209 |
|
| 210 |
if not self.options.autosummary_force_inline: |
| 211 |
docstring = self.get_doc() or [] |
| 212 |
autodocsumm_directive = '.. auto%ssumm::' % self.objtype |
| 213 |
for s in chain.from_iterable(docstring): |
| 214 |
if autodocsumm_directive in s: |
| 215 |
return {} |
| 216 |
|
| 217 |
# set the members from the autosummary member options |
| 218 |
options_save = {} |
| 219 |
for option in member_options.intersection(self.option_spec): |
| 220 |
autopt = 'autosummary-' + option |
| 221 |
if getattr(self.options, autopt): |
| 222 |
options_save[option] = getattr(self.options, option) |
| 223 |
self.options[option] = getattr(self.options, autopt) |
| 224 |
|
| 225 |
want_all = all_members or self.options.inherited_members or \ |
| 226 |
self.options.members is ALL |
| 227 |
# find out which members are documentable |
| 228 |
members_check_module, members = self.get_object_members(want_all) |
| 229 |
|
| 230 |
# remove members given by exclude-members |
| 231 |
if self.options.exclude_members: |
| 232 |
try: |
| 233 |
members = [ |
| 234 |
member for member in members |
| 235 |
if member.__name__ not in self.options.exclude_members |
| 236 |
] |
| 237 |
except AttributeError: # Sphinx<3.4.0 |
| 238 |
members = [ |
| 239 |
(membername, member) for (membername, member) in members |
| 240 |
if membername not in self.options.exclude_members |
| 241 |
] |
| 242 |
|
| 243 |
# document non-skipped members |
| 244 |
memberdocumenters = [] |
| 245 |
registry = self.env.app.registry.documenters |
| 246 |
|
| 247 |
for (mname, member, isattr) in self.filter_members(members, want_all): |
| 248 |
classes = [cls for cls in registry.values() |
| 249 |
if cls.can_document_member(member, mname, isattr, self)] |
| 250 |
if not classes: |
| 251 |
# don't know how to document this member |
| 252 |
continue |
| 253 |
# prefer the documenter with the highest priority |
| 254 |
classes.sort(key=lambda cls: cls.priority) |
| 255 |
# give explicitly separated module name, so that members |
| 256 |
# of inner classes can be documented |
| 257 |
full_mname = self.modname + '::' + \ |
| 258 |
'.'.join(self.objpath + [mname]) |
| 259 |
|
| 260 |
documenter = classes[-1](self.directive, full_mname, self.indent) |
| 261 |
memberdocumenters.append((documenter, |
| 262 |
members_check_module and not isattr)) |
| 263 |
|
| 264 |
member_order = ( |
| 265 |
self.options.member_order or self.env.config.autodoc_member_order |
| 266 |
) |
| 267 |
try: |
| 268 |
memberdocumenters = self.sort_members( |
| 269 |
memberdocumenters, member_order |
| 270 |
) |
| 271 |
except AttributeError: # sphinx<3.0 |
| 272 |
pass |
| 273 |
|
| 274 |
documenters = {} |
| 275 |
for e in memberdocumenters: |
| 276 |
section = self.member_sections.get( |
| 277 |
e[0].member_order, 'Miscellaneous') |
| 278 |
if self.env.app: |
| 279 |
e[0].parse_name() |
| 280 |
e[0].import_object() |
| 281 |
if members_check_module and not e[0].check_module(): |
| 282 |
continue |
| 283 |
user_section = self.env.app.emit_firstresult( |
| 284 |
'autodocsumm-grouper', self.objtype, e[0].object_name, |
| 285 |
e[0].object, section, self.object) |
| 286 |
section = user_section or section |
| 287 |
if not use_sections or section in use_sections: |
| 288 |
documenters.setdefault(section, []).append(e) |
| 289 |
self.options.update(options_save) |
| 290 |
|
| 291 |
sort_option = self.env.config.autodocsumm_section_sorter |
| 292 |
if sort_option is True: |
| 293 |
return {k: documenters[k] for k in sorted(documenters)} |
| 294 |
elif callable(sort_option): |
| 295 |
return {k: documenters[k] for k in sorted(documenters, key=sort_option)} |
| 296 |
else: |
| 297 |
return documenters |
| 298 |
|
| 299 |
def add_autosummary(self, relative_ref_paths=False): |
| 300 |
"""Add the autosammary table of this documenter. |
| 301 |
|
| 302 |
Parameters |
| 303 |
========== |
| 304 |
relative_ref_paths: bool |
| 305 |
Use paths relative to the current module instead of |
| 306 |
absolute import paths for each object |
| 307 |
""" |
| 308 |
if ( |
| 309 |
self.options.get("autosummary") |
| 310 |
and not self.options.get("no-autosummary") |
| 311 |
): |
| 312 |
|
| 313 |
grouped_documenters = self.get_grouped_documenters() |
| 314 |
|
| 315 |
sourcename = self.get_sourcename() |
| 316 |
|
| 317 |
for section, documenters in grouped_documenters.items(): |
| 318 |
if not self.options.autosummary_no_titles: |
| 319 |
self.add_line('**%s:**' % section, sourcename) |
| 320 |
|
| 321 |
self.add_line('', sourcename) |
| 322 |
|
| 323 |
self.add_line('.. autosummary::', sourcename) |
| 324 |
if self.options.autosummary_nosignatures: |
| 325 |
self.add_line(' :nosignatures:', sourcename) |
| 326 |
self.add_line('', sourcename) |
| 327 |
indent = ' ' |
| 328 |
|
| 329 |
for (documenter, _) in documenters: |
| 330 |
obj_ref_path = documenter.fullname |
| 331 |
if relative_ref_paths: |
| 332 |
modname = self.modname + "." |
| 333 |
if documenter.fullname.startswith(modname): |
| 334 |
obj_ref_path = documenter.fullname[len(modname):] |
| 335 |
|
| 336 |
self.add_line(indent + '~' + obj_ref_path, sourcename) |
| 337 |
|
| 338 |
self.add_line('', sourcename) |
| 339 |
|
| 340 |
|
| 341 |
class AutoSummModuleDocumenter(ModuleDocumenter, AutosummaryDocumenter): |
| 342 |
"""Module documentor with autosummary tables of its members. |
| 343 |
|
| 344 |
This class has the same functionality as the base |
| 345 |
:class:`sphinx.ext.autodoc.ModuleDocumenter` class but with an additional |
| 346 |
`autosummary`. |
| 347 |
It's priority is slightly higher than the one of the ModuleDocumenter. |
| 348 |
""" |
| 349 |
|
| 350 |
#: slightly higher priority than |
| 351 |
#: :class:`sphinx.ext.autodoc.ModuleDocumenter` |
| 352 |
priority = ModuleDocumenter.priority + 0.1 # type: ignore[assignment] |
| 353 |
|
| 354 |
#: original option_spec from :class:`sphinx.ext.autodoc.ModuleDocumenter` |
| 355 |
#: but with additional autosummary boolean option |
| 356 |
option_spec = ModuleDocumenter.option_spec.copy() |
| 357 |
option_spec['autosummary'] = bool_option |
| 358 |
option_spec['autosummary-no-nesting'] = bool_option |
| 359 |
option_spec['autosummary-sections'] = list_option |
| 360 |
option_spec['autosummary-no-titles'] = bool_option |
| 361 |
option_spec['autosummary-force-inline'] = bool_option |
| 362 |
option_spec['autosummary-nosignatures'] = bool_option |
| 363 |
|
| 364 |
#: Add options for members for the autosummary |
| 365 |
for _option in member_options.intersection(option_spec): |
| 366 |
option_spec['autosummary-' + _option] = option_spec[_option] |
| 367 |
del _option |
| 368 |
|
| 369 |
member_sections = { |
| 370 |
ad.ClassDocumenter.member_order: 'Classes', |
| 371 |
ad.ExceptionDocumenter.member_order: 'Exceptions', |
| 372 |
ad.FunctionDocumenter.member_order: 'Functions', |
| 373 |
ad.DataDocumenter.member_order: 'Data', |
| 374 |
} |
| 375 |
""":class:`dict` that includes the autosummary sections |
| 376 |
|
| 377 |
This dictionary defines the sections for the autosummmary option. The |
| 378 |
values correspond to the :attr:`sphinx.ext.autodoc.Documenter.member_order` |
| 379 |
attribute that shall be used for each section.""" |
| 380 |
|
| 381 |
def add_content(self, *args, **kwargs): |
| 382 |
super().add_content(*args, **kwargs) |
| 383 |
|
| 384 |
self.add_autosummary(relative_ref_paths=True) |
| 385 |
|
| 386 |
if self.options.get("autosummary-no-nesting"): |
| 387 |
self.options["no-autosummary"] = "True" |
| 388 |
|
| 389 |
|
| 390 |
class AutoSummClassDocumenter(ClassDocumenter, AutosummaryDocumenter): |
| 391 |
"""Class documentor with autosummary tables for its members. |
| 392 |
|
| 393 |
This class has the same functionality as the base |
| 394 |
:class:`sphinx.ext.autodoc.ClassDocumenter` class but with an additional |
| 395 |
`autosummary` option to provide the ability to provide a summary of all |
| 396 |
methods and attributes. |
| 397 |
It's priority is slightly higher than the one of the ClassDocumenter |
| 398 |
""" |
| 399 |
|
| 400 |
#: slightly higher priority than |
| 401 |
#: :class:`sphinx.ext.autodoc.ClassDocumenter` |
| 402 |
priority = ClassDocumenter.priority + 0.1 # type: ignore[assignment] |
| 403 |
|
| 404 |
#: original option_spec from :class:`sphinx.ext.autodoc.ClassDocumenter` |
| 405 |
#: but with additional autosummary boolean option |
| 406 |
option_spec = ClassDocumenter.option_spec.copy() |
| 407 |
option_spec['autosummary'] = bool_option |
| 408 |
option_spec['autosummary-no-nesting'] = bool_option |
| 409 |
option_spec['autosummary-sections'] = list_option |
| 410 |
option_spec['autosummary-no-titles'] = bool_option |
| 411 |
option_spec['autosummary-force-inline'] = bool_option |
| 412 |
option_spec['autosummary-nosignatures'] = bool_option |
| 413 |
|
| 414 |
#: Add options for members for the autosummary |
| 415 |
for _option in member_options.intersection(option_spec): |
| 416 |
option_spec['autosummary-' + _option] = option_spec[_option] |
| 417 |
del _option |
| 418 |
|
| 419 |
member_sections = { |
| 420 |
ad.ClassDocumenter.member_order: 'Classes', |
| 421 |
ad.MethodDocumenter.member_order: 'Methods', |
| 422 |
ad.AttributeDocumenter.member_order: 'Attributes', |
| 423 |
} |
| 424 |
""":class:`dict` that includes the autosummary sections |
| 425 |
|
| 426 |
This dictionary defines the sections for the autosummmary option. The |
| 427 |
values correspond to the :attr:`sphinx.ext.autodoc.Documenter.member_order` |
| 428 |
attribute that shall be used for each section.""" |
| 429 |
|
| 430 |
def add_content(self, *args, **kwargs): |
| 431 |
super().add_content(*args, **kwargs) |
| 432 |
|
| 433 |
# If the class is already documented under another name, Sphinx |
| 434 |
# documents it as data/attribute. In this case, we do not want to |
| 435 |
# generate an autosummary of the class for the attribute (see #69). |
| 436 |
if not self.doc_as_attr: |
| 437 |
self.add_autosummary(relative_ref_paths=True) |
| 438 |
|
| 439 |
|
| 440 |
class AutoSummExceptionDocumenter(ExceptionDocumenter, AutosummaryDocumenter): |
| 441 |
"""Exception Documenter with autosummary tables for its members. |
| 442 |
|
| 443 |
This class has the same functionality as the base |
| 444 |
:class:`sphinx.ext.autodoc.ExceptionDocumenter` class but with an |
| 445 |
additional `autosummary` option to provide the ability to provide a summary |
| 446 |
of all methods and attributes. |
| 447 |
It's priority is slightly higher than the one of the ExceptionDocumenter |
| 448 |
""" |
| 449 |
|
| 450 |
#: slightly higher priority than |
| 451 |
#: :class:`sphinx.ext.autodoc.ExceptionDocumenter` |
| 452 |
priority = ExceptionDocumenter.priority + 0.1 # type: ignore[assignment] |
| 453 |
|
| 454 |
#: original option_spec from |
| 455 |
#: :class:`sphinx.ext.autodoc.ExceptionDocumenter` but with additional |
| 456 |
#: autosummary boolean option |
| 457 |
option_spec = ExceptionDocumenter.option_spec.copy() |
| 458 |
option_spec['autosummary'] = bool_option |
| 459 |
option_spec['autosummary-no-nesting'] = bool_option |
| 460 |
option_spec['autosummary-sections'] = list_option |
| 461 |
option_spec['autosummary-no-titles'] = bool_option |
| 462 |
option_spec['autosummary-force-inline'] = bool_option |
| 463 |
option_spec['autosummary-nosignatures'] = bool_option |
| 464 |
|
| 465 |
#: Add options for members for the autosummary |
| 466 |
for _option in member_options.intersection(option_spec): |
| 467 |
option_spec['autosummary-' + _option] = option_spec[_option] |
| 468 |
del _option |
| 469 |
|
| 470 |
member_sections = { |
| 471 |
ad.ExceptionDocumenter.member_order: 'Classes', |
| 472 |
ad.MethodDocumenter.member_order: 'Methods', |
| 473 |
ad.AttributeDocumenter.member_order: 'Attributes', |
| 474 |
} |
| 475 |
""":class:`dict` that includes the autosummary sections |
| 476 |
|
| 477 |
This dictionary defines the sections for the autosummmary option. The |
| 478 |
values correspond to the :attr:`sphinx.ext.autodoc.Documenter.member_order` |
| 479 |
attribute that shall be used for each section.""" |
| 480 |
|
| 481 |
def add_content(self, *args, **kwargs): |
| 482 |
super().add_content(*args, **kwargs) |
| 483 |
|
| 484 |
# If the class is already documented under another name, Sphinx |
| 485 |
# documents it as data/attribute. In this case, we do not want to |
| 486 |
# generate an autosummary of the class for the attribute (see #69). |
| 487 |
if not self.doc_as_attr: |
| 488 |
self.add_autosummary(relative_ref_paths=True) |
| 489 |
|
| 490 |
|
| 491 |
class CallableDataDocumenter(DataDocumenter): |
| 492 |
""":class:`sphinx.ext.autodoc.DataDocumenter` that uses the __call__ attr |
| 493 |
""" |
| 494 |
|
| 495 |
#: slightly higher priority than |
| 496 |
#: :class:`sphinx.ext.autodoc.DataDocumenter` |
| 497 |
priority = DataDocumenter.priority + 0.1 # type: ignore[assignment] |
| 498 |
|
| 499 |
def format_args(self): |
| 500 |
# for classes, the relevant signature is the __init__ method's |
| 501 |
callmeth = self.get_attr(self.object, '__call__', None) |
| 502 |
if callmeth is None: |
| 503 |
return None |
| 504 |
return process_signature(callmeth) |
| 505 |
|
| 506 |
def get_doc(self, *args, **kwargs): |
| 507 |
"""Reimplemented to include data from the call method""" |
| 508 |
content = self.env.config.autodata_content |
| 509 |
if content not in ('both', 'call') or not self.get_attr( |
| 510 |
self.get_attr(self.object, '__call__', None), '__doc__'): |
| 511 |
return super(CallableDataDocumenter, self).get_doc( |
| 512 |
*args, **kwargs |
| 513 |
) |
| 514 |
|
| 515 |
# for classes, what the "docstring" is can be controlled via a |
| 516 |
# config value; the default is both docstrings |
| 517 |
docstrings = [] |
| 518 |
if content != 'call': |
| 519 |
docstring = self.get_attr(self.object, '__doc__', None) |
| 520 |
docstrings = [docstring + '\n'] if docstring else [] |
| 521 |
calldocstring = self.get_attr( |
| 522 |
self.get_attr(self.object, '__call__', None), '__doc__') |
| 523 |
if docstrings: |
| 524 |
docstrings[0] += calldocstring |
| 525 |
else: |
| 526 |
docstrings.append(calldocstring + '\n') |
| 527 |
|
| 528 |
doc = [] |
| 529 |
for docstring in docstrings: |
| 530 |
encoding = _get_arg("encoding", 0, None, *args, **kwargs) |
| 531 |
ignore = _get_arg("ignore", 1, 1, *args, **kwargs) |
| 532 |
if not isinstance(docstring, str): |
| 533 |
docstring = force_decode(docstring, encoding) |
| 534 |
doc.append(prepare_docstring(docstring)) |
| 535 |
|
| 536 |
return doc |
| 537 |
|
| 538 |
|
| 539 |
class CallableAttributeDocumenter(AttributeDocumenter): |
| 540 |
""":class:`sphinx.ext.autodoc.AttributeDocumenter` that uses the __call__ |
| 541 |
attr |
| 542 |
""" |
| 543 |
|
| 544 |
#: slightly higher priority than |
| 545 |
#: :class:`sphinx.ext.autodoc.AttributeDocumenter` |
| 546 |
priority = AttributeDocumenter.priority + 0.1 # type: ignore[assignment] |
| 547 |
|
| 548 |
def format_args(self): |
| 549 |
# for classes, the relevant signature is the __init__ method's |
| 550 |
callmeth = self.get_attr(self.object, '__call__', None) |
| 551 |
if callmeth is None: |
| 552 |
return None |
| 553 |
return process_signature(callmeth) |
| 554 |
|
| 555 |
def get_doc(self, *args, **kwargs): |
| 556 |
"""Reimplemented to include data from the call method""" |
| 557 |
content = self.env.config.autodata_content |
| 558 |
if content not in ('both', 'call') or not self.get_attr( |
| 559 |
self.get_attr(self.object, '__call__', None), '__doc__'): |
| 560 |
return super(CallableAttributeDocumenter, self).get_doc( |
| 561 |
*args, **kwargs |
| 562 |
) |
| 563 |
|
| 564 |
# for classes, what the "docstring" is can be controlled via a |
| 565 |
# config value; the default is both docstrings |
| 566 |
docstrings = [] |
| 567 |
if content != 'call': |
| 568 |
docstring = self.get_attr(self.object, '__doc__', None) |
| 569 |
docstrings = [docstring + '\n'] if docstring else [] |
| 570 |
calldocstring = self.get_attr( |
| 571 |
self.get_attr(self.object, '__call__', None), '__doc__') |
| 572 |
if docstrings: |
| 573 |
docstrings[0] += calldocstring |
| 574 |
else: |
| 575 |
docstrings.append(calldocstring + '\n') |
| 576 |
|
| 577 |
doc = [] |
| 578 |
if sphinx_version < [4, 0]: |
| 579 |
encoding = _get_arg("encoding", 0, None, *args, **kwargs) |
| 580 |
ignore = _get_arg("ignore", 1, 1, *args, **kwargs) |
| 581 |
for docstring in docstrings: |
| 582 |
if not isinstance(docstring, str): |
| 583 |
docstring = force_decode(docstring, encoding) |
| 584 |
doc.append(prepare_docstring(docstring, ignore)) |
| 585 |
else: |
| 586 |
for docstring in docstrings: |
| 587 |
doc.append(prepare_docstring(docstring)) |
| 588 |
|
| 589 |
return doc |
| 590 |
|
| 591 |
|
| 592 |
def dont_document_data(config, fullname): |
| 593 |
"""Check whether the given object should be documented |
| 594 |
|
| 595 |
Parameters |
| 596 |
---------- |
| 597 |
config: sphinx.Options |
| 598 |
The configuration |
| 599 |
fullname: str |
| 600 |
The name of the object |
| 601 |
|
| 602 |
Returns |
| 603 |
------- |
| 604 |
bool |
| 605 |
Whether the data of `fullname` should be excluded or not""" |
| 606 |
if config.document_data is True: |
| 607 |
document_data = [re.compile('.*')] |
| 608 |
else: |
| 609 |
document_data = config.document_data |
| 610 |
if config.not_document_data is True: |
| 611 |
not_document_data = [re.compile('.*')] |
| 612 |
else: |
| 613 |
not_document_data = config.not_document_data |
| 614 |
return ( |
| 615 |
# data should not be documented |
| 616 |
(any(re.match(p, fullname) for p in not_document_data)) or |
| 617 |
# or data is not included in what should be documented |
| 618 |
(not any(re.match(p, fullname) for p in document_data))) |
| 619 |
|
| 620 |
|
| 621 |
class NoDataDataDocumenter(CallableDataDocumenter): |
| 622 |
"""DataDocumenter that prevents the displaying of large data""" |
| 623 |
|
| 624 |
#: slightly higher priority as the one of the CallableDataDocumenter |
| 625 |
priority = CallableDataDocumenter.priority + 0.1 # type: ignore[assignment] |
| 626 |
|
| 627 |
def __init__(self, *args, **kwargs): |
| 628 |
super(NoDataDataDocumenter, self).__init__(*args, **kwargs) |
| 629 |
fullname = '.'.join(self.name.rsplit('::', 1)) |
| 630 |
if hasattr(self.env, 'config') and dont_document_data( |
| 631 |
self.env.config, fullname): |
| 632 |
self.options = Options(self.options) |
| 633 |
self.options.annotation = ' ' |
| 634 |
|
| 635 |
|
| 636 |
class NoDataAttributeDocumenter(CallableAttributeDocumenter): |
| 637 |
"""AttributeDocumenter that prevents the displaying of large data""" |
| 638 |
|
| 639 |
#: slightly higher priority as the one of the CallableAttributeDocumenter |
| 640 |
priority = CallableAttributeDocumenter.priority + 0.1 # type: ignore[assignment] |
| 641 |
|
| 642 |
def __init__(self, *args, **kwargs): |
| 643 |
super(NoDataAttributeDocumenter, self).__init__(*args, **kwargs) |
| 644 |
fullname = '.'.join(self.name.rsplit('::', 1)) |
| 645 |
if hasattr(self.env, 'config') and dont_document_data( |
| 646 |
self.env.config, fullname): |
| 647 |
self.options = Options(self.options) |
| 648 |
self.options.annotation = ' ' |
| 649 |
|
| 650 |
|
| 651 |
class AutoDocSummDirective(SphinxDirective): |
| 652 |
"""A directive to generate an autosummary. |
| 653 |
|
| 654 |
Usage:: |
| 655 |
|
| 656 |
.. autoclasssumm:: <Class> |
| 657 |
|
| 658 |
.. automodsumm:: <module> |
| 659 |
|
| 660 |
.. autoexceptionsumm:: <ExceptionClass> |
| 661 |
|
| 662 |
The directive additionally supports all options of the ``autoclass``, |
| 663 |
``automod``, or ``autoexception`` directive respectively. Sections can be a |
| 664 |
list of section titles to be included. If ommitted, all sections are used. |
| 665 |
""" |
| 666 |
|
| 667 |
has_content = False |
| 668 |
|
| 669 |
option_spec = AutodocDirective.option_spec |
| 670 |
|
| 671 |
required_arguments = 1 |
| 672 |
optional_arguments = 0 |
| 673 |
|
| 674 |
def run(self): |
| 675 |
reporter = self.state.document.reporter |
| 676 |
|
| 677 |
try: |
| 678 |
_, lineno = reporter.get_source_and_line(self.lineno) |
| 679 |
except AttributeError: |
| 680 |
_, lineno = (None, None) |
| 681 |
|
| 682 |
# look up target Documenter |
| 683 |
objtype = self.name[4:-4] # strip prefix (auto-) and suffix (-summ). |
| 684 |
doccls = self.env.app.registry.documenters[objtype] |
| 685 |
|
| 686 |
self.options['autosummary-force-inline'] = "True" |
| 687 |
self.options['autosummary'] = "True" |
| 688 |
if 'no-members' not in self.options: |
| 689 |
self.options['members'] = "" |
| 690 |
|
| 691 |
# process the options with the selected documenter's option_spec |
| 692 |
try: |
| 693 |
documenter_options = process_documenter_options(doccls, self.config, |
| 694 |
self.options) |
| 695 |
except (KeyError, ValueError, TypeError) as exc: |
| 696 |
# an option is either unknown or has a wrong type |
| 697 |
logger.error( |
| 698 |
'An option to %s is either unknown or has an invalid ' |
| 699 |
'value: %s', self.name, exc, |
| 700 |
location=(self.env.docname, lineno)) |
| 701 |
return [] |
| 702 |
|
| 703 |
# generate the output |
| 704 |
params = DocumenterBridge(self.env, reporter, documenter_options, |
| 705 |
lineno, self.state) |
| 706 |
documenter = doccls(params, self.arguments[0]) |
| 707 |
documenter.add_autosummary() |
| 708 |
|
| 709 |
node = nodes.paragraph() |
| 710 |
node.document = self.state.document |
| 711 |
self.state.nested_parse(params.result, 0, node) |
| 712 |
|
| 713 |
return node.children |
| 714 |
|
| 715 |
|
| 716 |
def setup(app): |
| 717 |
"""setup function for using this module as a sphinx extension""" |
| 718 |
app.setup_extension('sphinx.ext.autosummary') |
| 719 |
app.setup_extension('sphinx.ext.autodoc') |
| 720 |
app.add_directive('autoclasssumm', AutoDocSummDirective) |
| 721 |
app.add_directive('autoexceptionsumm', AutoDocSummDirective) |
| 722 |
app.add_directive('automodulesumm', AutoDocSummDirective) |
| 723 |
|
| 724 |
AUTODOC_DEFAULT_OPTIONS.extend( |
| 725 |
[option for option in AutoSummModuleDocumenter.option_spec |
| 726 |
if option not in AUTODOC_DEFAULT_OPTIONS]) |
| 727 |
|
| 728 |
AUTODOC_DEFAULT_OPTIONS.extend( |
| 729 |
[option for option in AutoSummClassDocumenter.option_spec |
| 730 |
if option not in AUTODOC_DEFAULT_OPTIONS]) |
| 731 |
|
| 732 |
# make sure to allow inheritance when registering new documenters |
| 733 |
registry = app.registry.documenters |
| 734 |
for cls in [AutoSummClassDocumenter, AutoSummModuleDocumenter, |
| 735 |
CallableAttributeDocumenter, NoDataDataDocumenter, |
| 736 |
NoDataAttributeDocumenter, AutoSummExceptionDocumenter]: |
| 737 |
if not issubclass(registry.get(cls.objtype), cls): |
| 738 |
app.add_autodocumenter(cls, override=True) |
| 739 |
|
| 740 |
# group event |
| 741 |
app.add_event('autodocsumm-grouper') |
| 742 |
|
| 743 |
# config value |
| 744 |
app.add_config_value('autodata_content', 'class', True) |
| 745 |
app.add_config_value('document_data', True, True) |
| 746 |
app.add_config_value('not_document_data', [], True) |
| 747 |
app.add_config_value('autodocsumm_section_sorter', None, True) |
| 748 |
return {'version': sphinx.__display_version__, 'parallel_read_safe': True} |
| 749 |
|
| 750 |
|