Debian Codegraph @

autodocsumm/__init__.py

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