Debian Codegraph @

src/mkdocstrings_handlers/python/_internal/config.py

raw
1 # Configuration and options dataclasses.
2
3 from __future__ import annotations
4
5 import re
6 import sys
7 from dataclasses import field, fields
8 from typing import TYPE_CHECKING, Annotated, Any, Literal
9
10 from mkdocstrings import get_logger
11
12 from mkdocstrings_handlers.python._internal.rendering import Order # noqa: TC001
13
14 # YORE: EOL 3.10: Replace block with line 2.
15 if sys.version_info >= (3, 11):
16 from typing import Self
17 else:
18 from typing_extensions import Self
19
20
21 _logger = get_logger(__name__)
22
23 _DEFAULT_FILTERS = ["!^_[^_]"]
24
25 try:
26 # When Pydantic is available, use it to validate options (done automatically).
27 # Users can therefore opt into validation by installing Pydantic in development/CI.
28 # When building the docs to deploy them, Pydantic is not required anymore.
29
30 # When building our own docs, Pydantic is always installed (see `docs` group in `pyproject.toml`)
31 # to allow automatic generation of a JSON Schema. The JSON Schema is then referenced by mkdocstrings,
32 # which is itself referenced by mkdocs-material's schema system. For example in VSCode:
33 #
34 # "yaml.schemas": {
35 # "https://squidfunk.github.io/mkdocs-material/schema.json": "mkdocs.yml"
36 # }
37 import pydantic
38
39 if getattr(pydantic, "__version__", "1.").startswith("1."):
40 raise ImportError # noqa: TRY301
41
42 from inspect import cleandoc
43
44 from pydantic import Field as BaseField
45 from pydantic.dataclasses import dataclass
46
47 _base_url = "https://mkdocstrings.github.io/python/usage"
48
49 def _Field( # noqa: N802
50 *args: Any,
51 description: str,
52 group: Literal["general", "headings", "members", "docstrings", "signatures"] | None = None,
53 parent: str | None = None,
54 **kwargs: Any,
55 ) -> None:
56 def _add_markdown_description(schema: dict[str, Any]) -> None:
57 url = f"{_base_url}/{f'configuration/{group}/' if group else ''}#{parent or schema['title']}"
58 schema["markdownDescription"] = f"[DOCUMENTATION]({url})\n\n{schema['description']}"
59
60 return BaseField(
61 *args,
62 description=cleandoc(description),
63 field_title_generator=lambda name, _: name,
64 json_schema_extra=_add_markdown_description,
65 **kwargs,
66 )
67 except ImportError:
68 from dataclasses import dataclass # type: ignore[no-redef]
69
70 def _Field(*args: Any, **kwargs: Any) -> None: # type: ignore[misc] # noqa: N802
71 pass
72
73
74 if TYPE_CHECKING:
75 from collections.abc import MutableMapping
76
77
78 @dataclass(frozen=True, kw_only=True)
79 class GoogleStyleOptions:
80 """Google style docstring options."""
81
82 ignore_init_summary: Annotated[
83 bool,
84 _Field(
85 group="docstrings",
86 parent="docstring_options",
87 description="Whether to ignore the summary in `__init__` methods' docstrings.",
88 ),
89 ] = False
90
91 returns_multiple_items: Annotated[
92 bool,
93 _Field(
94 group="docstrings",
95 parent="docstring_options",
96 description="""Whether to parse multiple items in `Yields` and `Returns` sections.
97
98 When true, each item's continuation lines must be indented.
99 When false (single item), no further indentation is required.
100 """,
101 ),
102 ] = True
103
104 returns_named_value: Annotated[
105 bool,
106 _Field(
107 group="docstrings",
108 parent="docstring_options",
109 description="""Whether to parse `Yields` and `Returns` section items as name and description, rather than type and description.
110
111 When true, type must be wrapped in parentheses: `(int): Description.`. Names are optional: `name (int): Description.`.
112 When false, parentheses are optional but the items cannot be named: `int: Description`.
113 """,
114 ),
115 ] = True
116
117 returns_type_in_property_summary: Annotated[
118 bool,
119 _Field(
120 group="docstrings",
121 parent="docstring_options",
122 description="Whether to parse the return type of properties at the beginning of their summary: `str: Summary of the property`.",
123 ),
124 ] = False
125
126 receives_multiple_items: Annotated[
127 bool,
128 _Field(
129 group="docstrings",
130 parent="docstring_options",
131 description="""Whether to parse multiple items in `Receives` sections.
132
133 When true, each item's continuation lines must be indented.
134 When false (single item), no further indentation is required.
135 """,
136 ),
137 ] = True
138
139 receives_named_value: Annotated[
140 bool,
141 _Field(
142 group="docstrings",
143 parent="docstring_options",
144 description="""Whether to parse `Receives` section items as name and description, rather than type and description.
145
146 When true, type must be wrapped in parentheses: `(int): Description.`. Names are optional: `name (int): Description.`.
147 When false, parentheses are optional but the items cannot be named: `int: Description`.
148 """,
149 ),
150 ] = True
151
152 trim_doctest_flags: Annotated[
153 bool,
154 _Field(
155 group="docstrings",
156 parent="docstring_options",
157 description="Whether to remove doctest flags from Python example blocks.",
158 ),
159 ] = True
160
161 warn_unknown_params: Annotated[
162 bool,
163 _Field(
164 group="docstrings",
165 parent="docstring_options",
166 description="Warn about documented parameters not appearing in the signature.",
167 ),
168 ] = True
169
170 warn_missing_types: Annotated[
171 bool,
172 _Field(
173 group="docstrings",
174 parent="docstring_options",
175 description="Warn about missing type/annotation for parameters, return values, etc.",
176 ),
177 ] = True
178
179 warnings: Annotated[
180 bool,
181 _Field(
182 group="docstrings",
183 parent="docstring_options",
184 description="Generally enable/disable warnings when parsing docstrings.",
185 ),
186 ] = True
187
188
189 @dataclass(frozen=True, kw_only=True)
190 class NumpyStyleOptions:
191 """Numpy style docstring options."""
192
193 ignore_init_summary: Annotated[
194 bool,
195 _Field(
196 group="docstrings",
197 parent="docstring_options",
198 description="Whether to ignore the summary in `__init__` methods' docstrings.",
199 ),
200 ] = False
201
202 trim_doctest_flags: Annotated[
203 bool,
204 _Field(
205 group="docstrings",
206 parent="docstring_options",
207 description="Whether to remove doctest flags from Python example blocks.",
208 ),
209 ] = True
210
211 warn_unknown_params: Annotated[
212 bool,
213 _Field(
214 group="docstrings",
215 parent="docstring_options",
216 description="Warn about documented parameters not appearing in the signature.",
217 ),
218 ] = True
219
220 warn_missing_types: Annotated[
221 bool,
222 _Field(
223 group="docstrings",
224 parent="docstring_options",
225 description="Warn about missing type/annotation for parameters, return values, etc.",
226 ),
227 ] = True
228
229 warnings: Annotated[
230 bool,
231 _Field(
232 group="docstrings",
233 parent="docstring_options",
234 description="Generally enable/disable warnings when parsing docstrings.",
235 ),
236 ] = True
237
238
239 @dataclass(frozen=True, kw_only=True)
240 class SphinxStyleOptions:
241 """Sphinx style docstring options."""
242
243 warn_unknown_params: Annotated[
244 bool,
245 _Field(
246 group="docstrings",
247 parent="docstring_options",
248 description="Warn about documented parameters not appearing in the signature.",
249 ),
250 ] = True
251
252 warn_missing_types: Annotated[
253 bool,
254 _Field(
255 group="docstrings",
256 parent="docstring_options",
257 description="Warn about missing type/annotation for return values.",
258 ),
259 ] = True
260
261 warnings: Annotated[
262 bool,
263 _Field(
264 group="docstrings",
265 parent="docstring_options",
266 description="Generally enable/disable warnings when parsing docstrings.",
267 ),
268 ] = True
269
270
271 @dataclass(frozen=True, kw_only=True)
272 class PerStyleOptions:
273 """Per style options."""
274
275 google: Annotated[
276 GoogleStyleOptions,
277 _Field(
278 group="docstrings",
279 parent="docstring_options",
280 description="Google-style options.",
281 ),
282 ] = field(default_factory=GoogleStyleOptions)
283
284 numpy: Annotated[
285 NumpyStyleOptions,
286 _Field(
287 group="docstrings",
288 parent="docstring_options",
289 description="Numpydoc-style options.",
290 ),
291 ] = field(default_factory=NumpyStyleOptions)
292
293 sphinx: Annotated[
294 SphinxStyleOptions,
295 _Field(
296 group="docstrings",
297 parent="docstring_options",
298 description="Sphinx-style options.",
299 ),
300 ] = field(default_factory=SphinxStyleOptions)
301
302 @classmethod
303 def from_data(cls, **data: Any) -> Self:
304 """Create an instance from a dictionary."""
305 if "google" in data:
306 data["google"] = GoogleStyleOptions(**data["google"])
307 if "numpy" in data:
308 data["numpy"] = NumpyStyleOptions(**data["numpy"])
309 if "sphinx" in data:
310 data["sphinx"] = SphinxStyleOptions(**data["sphinx"])
311 return cls(**data)
312
313
314 @dataclass(frozen=True, kw_only=True)
315 class AutoStyleOptions:
316 """Auto style docstring options."""
317
318 method: Annotated[
319 Literal["heuristics", "max_sections"],
320 _Field(
321 group="docstrings",
322 parent="docstring_options",
323 description="The method to use to determine the docstring style.",
324 ),
325 ] = "heuristics"
326
327 style_order: Annotated[
328 list[str],
329 _Field(
330 group="docstrings",
331 parent="docstring_options",
332 description="The order of the docstring styles to try.",
333 ),
334 ] = field(default_factory=lambda: ["sphinx", "google", "numpy"])
335
336 default: Annotated[
337 str | None,
338 _Field(
339 group="docstrings",
340 parent="docstring_options",
341 description="The default docstring style to use if no other style is detected.",
342 ),
343 ] = None
344
345 per_style_options: Annotated[
346 PerStyleOptions,
347 _Field(
348 group="docstrings",
349 parent="docstring_options",
350 description="Per-style options.",
351 ),
352 ] = field(default_factory=PerStyleOptions)
353
354 @classmethod
355 def from_data(cls, **data: Any) -> Self:
356 """Create an instance from a dictionary."""
357 if "per_style_options" in data:
358 data["per_style_options"] = PerStyleOptions.from_data(**data["per_style_options"])
359 return cls(**data)
360
361
362 @dataclass(frozen=True, kw_only=True)
363 class SummaryOption:
364 """Summary option."""
365
366 attributes: Annotated[
367 bool,
368 _Field(
369 group="members",
370 parent="summary",
371 description="Whether to render summaries of attributes.",
372 ),
373 ] = False
374
375 functions: Annotated[
376 bool,
377 _Field(
378 group="members",
379 parent="summary",
380 description="Whether to render summaries of functions (methods).",
381 ),
382 ] = False
383
384 classes: Annotated[
385 bool,
386 _Field(
387 group="members",
388 parent="summary",
389 description="Whether to render summaries of classes.",
390 ),
391 ] = False
392
393 modules: Annotated[
394 bool,
395 _Field(
396 group="members",
397 parent="summary",
398 description="Whether to render summaries of modules.",
399 ),
400 ] = False
401
402 type_aliases: Annotated[
403 bool,
404 _Field(
405 group="members",
406 parent="summary",
407 description="Whether to render summaries of type aliases.",
408 ),
409 ] = False
410
411
412 @dataclass(frozen=True, kw_only=True)
413 class PythonInputOptions:
414 """Accepted input options."""
415
416 allow_inspection: Annotated[
417 bool,
418 _Field(
419 group="general",
420 description="Whether to allow inspecting modules when visiting them is not possible.",
421 ),
422 ] = True
423
424 force_inspection: Annotated[
425 bool,
426 _Field(
427 group="general",
428 description="Whether to force using dynamic analysis when loading data.",
429 ),
430 ] = False
431
432 annotations_path: Annotated[
433 Literal["brief", "source", "full"],
434 _Field(
435 group="signatures",
436 description="The verbosity for annotations path: `brief` (recommended), `source` (as written in the source), or `full`.",
437 ),
438 ] = "brief"
439
440 backlinks: Annotated[
441 Literal["flat", "tree", False],
442 _Field(
443 group="general",
444 description="Whether to render backlinks, and how.",
445 ),
446 ] = False
447
448 docstring_options: Annotated[
449 GoogleStyleOptions | NumpyStyleOptions | SphinxStyleOptions | AutoStyleOptions | None,
450 _Field(
451 group="docstrings",
452 description="""The options for the docstring parser.
453
454 See [docstring parsers](https://mkdocstrings.github.io/griffe/reference/docstrings/) and their options in Griffe docs.
455 """,
456 ),
457 ] = None
458
459 docstring_section_style: Annotated[
460 Literal["table", "list", "spacy"],
461 _Field(
462 group="docstrings",
463 description="The style used to render docstring sections.",
464 ),
465 ] = "table"
466
467 docstring_style: Annotated[
468 Literal["auto", "google", "numpy", "sphinx"] | None,
469 _Field(
470 group="docstrings",
471 description="The docstring style to use: `auto`, `google`, `numpy`, `sphinx`, or `None`.",
472 ),
473 ] = "google"
474
475 extensions: Annotated[
476 list[str | dict[str, Any]],
477 _Field(
478 group="general",
479 description="A list of Griffe extensions to load.",
480 ),
481 ] = field(default_factory=list)
482
483 filters: Annotated[
484 list[str] | Literal["public"],
485 _Field(
486 group="members",
487 description="""A list of filters, or `"public"`.
488
489 **List of filters**
490
491 A filter starting with `!` will exclude matching objects instead of including them.
492 The `members` option takes precedence over `filters` (filters will still be applied recursively
493 to lower members in the hierarchy).
494
495 **Filtering methods**
496
497 The `public` method will include only public objects:
498 those added to `__all__` or not starting with an underscore (except for special methods/attributes).
499 """,
500 ),
501 ] = field(default_factory=_DEFAULT_FILTERS.copy)
502
503 find_stubs_package: Annotated[
504 bool,
505 _Field(
506 group="general",
507 description="Whether to load stubs package (package-stubs) when extracting docstrings.",
508 ),
509 ] = False
510
511 group_by_category: Annotated[
512 bool,
513 _Field(
514 group="members",
515 description="Group the object's children by categories: attributes, classes, functions, and modules.",
516 ),
517 ] = True
518
519 heading: Annotated[
520 str,
521 _Field(
522 group="headings",
523 description="A custom string to override the autogenerated heading of the root object.",
524 ),
525 ] = ""
526
527 heading_level: Annotated[
528 int,
529 _Field(
530 group="headings",
531 description="The initial heading level to use.",
532 ),
533 ] = 2
534
535 inheritance_diagram_direction: Annotated[
536 Literal["TB", "TD", "BT", "RL", "LR"],
537 _Field(
538 group="docstrings",
539 description="The direction of the Mermaid chart presenting the inheritance diagram of a class.",
540 ),
541 ] = "TD"
542
543 inherited_members: Annotated[
544 bool | list[str],
545 _Field(
546 group="members",
547 description="""A boolean, or an explicit list of inherited members to render.
548
549 If true, select all inherited members, which can then be filtered with `members`.
550 If false or empty list, do not select any inherited member.
551 """,
552 ),
553 ] = False
554
555 line_length: Annotated[
556 int,
557 _Field(
558 group="signatures",
559 description="Maximum line length when formatting code/signatures.",
560 ),
561 ] = 60
562
563 members: Annotated[
564 list[str] | bool | None,
565 _Field(
566 group="members",
567 description="""A boolean, or an explicit list of members to render.
568
569 If true, select all members without further filtering.
570 If false or empty list, do not render members.
571 If none, select all members and apply further filtering with filters and docstrings.
572 """,
573 ),
574 ] = None
575
576 members_order: Annotated[
577 Order | list[Order],
578 _Field(
579 group="members",
580 description="""The members ordering to use.
581
582 - `__all__`: order members according to `__all__` module attributes, if declared;
583 - `alphabetical`: order members alphabetically;
584 - `source`: order members as they appear in the source file.
585
586 Since `__all__` is a module-only attribute, it can't be used to sort class members,
587 therefore the `members_order` option accepts a list of ordering methods,
588 indicating ordering preferences.
589 """,
590 ),
591 ] = "alphabetical"
592
593 merge_init_into_class: Annotated[
594 bool,
595 _Field(
596 group="docstrings",
597 description="Whether to merge the `__init__` method into the class' signature and docstring.",
598 ),
599 ] = False
600
601 modernize_annotations: Annotated[
602 bool,
603 _Field(
604 group="signatures",
605 description="Whether to modernize annotations, for example `Optional[str]` into `str | None`.",
606 ),
607 ] = False
608
609 overloads_only: Annotated[
610 bool,
611 _Field(
612 group="signatures",
613 description="Whether to hide the implementation signature if the overloads are shown.",
614 ),
615 ] = False
616
617 parameter_headings: Annotated[
618 bool,
619 _Field(
620 group="headings",
621 description="Whether to render headings for parameters (therefore showing parameters in the ToC).",
622 ),
623 ] = False
624
625 preload_modules: Annotated[
626 list[str],
627 _Field(
628 group="general",
629 description="""Pre-load modules that are not specified directly in autodoc instructions (`::: identifier`).
630
631 It is useful when you want to render documentation for a particular member of an object,
632 and this member is imported from another package than its parent.
633
634 For an imported member to be rendered, you need to add it to the `__all__` attribute
635 of the importing module.
636
637 The modules must be listed as an array of strings.
638 """,
639 ),
640 ] = field(default_factory=list)
641
642 relative_crossrefs: Annotated[
643 bool,
644 _Field(
645 group="docstrings",
646 description="Whether to enable the relative crossref syntax.",
647 ),
648 ] = False
649
650 scoped_crossrefs: Annotated[
651 bool,
652 _Field(
653 group="docstrings",
654 description="Whether to enable the scoped crossref ability.",
655 ),
656 ] = False
657
658 show_overloads: Annotated[
659 bool,
660 _Field(
661 group="signatures",
662 description="Show the overloads of a function or method.",
663 ),
664 ] = True
665
666 separate_signature: Annotated[
667 bool,
668 _Field(
669 group="signatures",
670 description="""Whether to put the whole signature in a code block below the heading.
671
672 If Black or Ruff are installed, the signature is also formatted using them.
673 """,
674 ),
675 ] = False
676
677 show_attribute_values: Annotated[
678 bool,
679 _Field(
680 group="signatures",
681 description="Show initial values of attributes in classes.",
682 ),
683 ] = True
684
685 show_bases: Annotated[
686 bool,
687 _Field(
688 group="general",
689 description="Show the base classes of a class.",
690 ),
691 ] = True
692
693 show_category_heading: Annotated[
694 bool,
695 _Field(
696 group="headings",
697 description="When grouped by categories, show a heading for each category.",
698 ),
699 ] = False
700
701 show_docstring_attributes: Annotated[
702 bool,
703 _Field(
704 group="docstrings",
705 description="Whether to display the 'Attributes' section in the object's docstring.",
706 ),
707 ] = True
708
709 show_docstring_classes: Annotated[
710 bool,
711 _Field(
712 group="docstrings",
713 description="Whether to display the 'Classes' section in the object's docstring.",
714 ),
715 ] = True
716
717 show_docstring_description: Annotated[
718 bool,
719 _Field(
720 group="docstrings",
721 description="Whether to display the textual block (including admonitions) in the object's docstring.",
722 ),
723 ] = True
724
725 show_docstring_examples: Annotated[
726 bool,
727 _Field(
728 group="docstrings",
729 description="Whether to display the 'Examples' section in the object's docstring.",
730 ),
731 ] = True
732
733 show_docstring_functions: Annotated[
734 bool,
735 _Field(
736 group="docstrings",
737 description="Whether to display the 'Functions' or 'Methods' sections in the object's docstring.",
738 ),
739 ] = True
740
741 show_docstring_modules: Annotated[
742 bool,
743 _Field(
744 group="docstrings",
745 description="Whether to display the 'Modules' section in the object's docstring.",
746 ),
747 ] = True
748
749 show_docstring_other_parameters: Annotated[
750 bool,
751 _Field(
752 group="docstrings",
753 description="Whether to display the 'Other Parameters' section in the object's docstring.",
754 ),
755 ] = True
756
757 show_docstring_parameters: Annotated[
758 bool,
759 _Field(
760 group="docstrings",
761 description="Whether to display the 'Parameters' section in the object's docstring.",
762 ),
763 ] = True
764
765 show_docstring_raises: Annotated[
766 bool,
767 _Field(
768 group="docstrings",
769 description="Whether to display the 'Raises' section in the object's docstring.",
770 ),
771 ] = True
772
773 show_docstring_receives: Annotated[
774 bool,
775 _Field(
776 group="docstrings",
777 description="Whether to display the 'Receives' section in the object's docstring.",
778 ),
779 ] = True
780
781 show_docstring_returns: Annotated[
782 bool,
783 _Field(
784 group="docstrings",
785 description="Whether to display the 'Returns' section in the object's docstring.",
786 ),
787 ] = True
788
789 show_docstring_type_aliases: Annotated[
790 bool,
791 _Field(
792 group="docstrings",
793 description="Whether to display the 'Type Aliases' section in the object's docstring.",
794 ),
795 ] = True
796
797 show_docstring_type_parameters: Annotated[
798 bool,
799 _Field(
800 group="docstrings",
801 description="Whether to display the 'Type Parameters' section in the object's docstring.",
802 ),
803 ] = True
804
805 show_docstring_warns: Annotated[
806 bool,
807 _Field(
808 group="docstrings",
809 description="Whether to display the 'Warns' section in the object's docstring.",
810 ),
811 ] = True
812
813 show_docstring_yields: Annotated[
814 bool,
815 _Field(
816 group="docstrings",
817 description="Whether to display the 'Yields' section in the object's docstring.",
818 ),
819 ] = True
820
821 show_if_no_docstring: Annotated[
822 bool,
823 _Field(
824 group="docstrings",
825 description="Show the object heading even if it has no docstring or children with docstrings.",
826 ),
827 ] = False
828
829 show_inheritance_diagram: Annotated[
830 bool,
831 _Field(
832 group="docstrings",
833 description="Show the inheritance diagram of a class using Mermaid.",
834 ),
835 ] = False
836
837 show_labels: Annotated[
838 bool,
839 _Field(
840 group="docstrings",
841 description="Whether to show labels of the members.",
842 ),
843 ] = True
844
845 show_object_full_path: Annotated[
846 bool,
847 _Field(
848 group="docstrings",
849 description="Show the full Python path of every object.",
850 ),
851 ] = False
852
853 show_root_full_path: Annotated[
854 bool,
855 _Field(
856 group="docstrings",
857 description="Show the full Python path for the root object heading.",
858 ),
859 ] = True
860
861 show_root_heading: Annotated[
862 bool,
863 _Field(
864 group="headings",
865 description="""Show the heading of the object at the root of the documentation tree.
866
867 The root object is the object referenced by the identifier after `:::`.
868 """,
869 ),
870 ] = False
871
872 show_root_members_full_path: Annotated[
873 bool,
874 _Field(
875 group="headings",
876 description="Show the full Python path of the root members.",
877 ),
878 ] = False
879
880 show_root_toc_entry: Annotated[
881 bool,
882 _Field(
883 group="headings",
884 description="If the root heading is not shown, at least add a ToC entry for it.",
885 ),
886 ] = True
887
888 show_signature_annotations: Annotated[
889 bool,
890 _Field(
891 group="signatures",
892 description="Show the type annotations in methods and functions signatures.",
893 ),
894 ] = False
895
896 show_signature_type_parameters: Annotated[
897 bool,
898 _Field(
899 group="signatures",
900 description="Show the type parameters in generic classes, methods, functions and type aliases signatures.",
901 ),
902 ] = False
903
904 show_signature: Annotated[
905 bool,
906 _Field(
907 group="signatures",
908 description="Show methods and functions signatures.",
909 ),
910 ] = True
911
912 show_source: Annotated[
913 bool,
914 _Field(
915 group="general",
916 description="Show the source code of this object.",
917 ),
918 ] = True
919
920 show_submodules: Annotated[
921 bool,
922 _Field(
923 group="members",
924 description="When rendering a module, show its submodules recursively.",
925 ),
926 ] = False
927
928 show_symbol_type_heading: Annotated[
929 bool,
930 _Field(
931 group="headings",
932 description="Show the symbol type in headings (e.g. mod, class, meth, func and attr).",
933 ),
934 ] = False
935
936 show_symbol_type_toc: Annotated[
937 bool,
938 _Field(
939 group="headings",
940 description="Show the symbol type in the Table of Contents (e.g. mod, class, methd, func and attr).",
941 ),
942 ] = False
943
944 skip_local_inventory: Annotated[
945 bool,
946 _Field(
947 group="general",
948 description="Whether to prevent objects from being registered in the local objects inventory.",
949 ),
950 ] = False
951
952 signature_crossrefs: Annotated[
953 bool,
954 _Field(
955 group="signatures",
956 description="Whether to render cross-references for type annotations in signatures.",
957 ),
958 ] = False
959
960 summary: Annotated[
961 bool | SummaryOption,
962 _Field(
963 group="members",
964 description="Whether to render summaries of modules, classes, functions (methods) and attributes.",
965 ),
966 ] = field(default_factory=SummaryOption)
967
968 toc_label: Annotated[
969 str,
970 _Field(
971 group="headings",
972 description="A custom string to override the autogenerated toc label of the root object.",
973 ),
974 ] = ""
975
976 type_parameter_headings: Annotated[
977 bool,
978 _Field(
979 group="headings",
980 description="Whether to render headings for type parameters (therefore showing type parameters in the ToC).",
981 ),
982 ] = False
983
984 unwrap_annotated: Annotated[
985 bool,
986 _Field(
987 group="signatures",
988 description="Whether to unwrap `Annotated` types to show only the type without the annotations.",
989 ),
990 ] = False
991
992 extra: Annotated[
993 dict[str, Any],
994 _Field(
995 group="general",
996 description="Extra options.",
997 ),
998 ] = field(default_factory=dict)
999
1000 @classmethod
1001 def _extract_extra(cls, data: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
1002 field_names = {field.name for field in fields(cls)}
1003 copy = data.copy()
1004 return {name: copy.pop(name) for name in data if name not in field_names}, copy
1005
1006 @classmethod
1007 def coerce(cls, **data: Any) -> MutableMapping[str, Any]:
1008 """Coerce data."""
1009 if "docstring_options" in data:
1010 docstring_style = data.get("docstring_style", "google")
1011 docstring_options = data["docstring_options"]
1012 if docstring_options is not None:
1013 if docstring_style == "auto":
1014 docstring_options = AutoStyleOptions.from_data(**docstring_options)
1015 elif docstring_style == "google":
1016 docstring_options = GoogleStyleOptions(**docstring_options)
1017 elif docstring_style == "numpy":
1018 docstring_options = NumpyStyleOptions(**docstring_options)
1019 elif docstring_style == "sphinx":
1020 docstring_options = SphinxStyleOptions(**docstring_options)
1021 data["docstring_options"] = docstring_options
1022 if "summary" in data:
1023 summary = data["summary"]
1024 if summary is True:
1025 summary = SummaryOption(attributes=True, functions=True, classes=True, modules=True, type_aliases=True)
1026 elif summary is False:
1027 summary = SummaryOption(
1028 attributes=False,
1029 functions=False,
1030 classes=False,
1031 modules=False,
1032 type_aliases=False,
1033 )
1034 else:
1035 summary = SummaryOption(**summary)
1036 data["summary"] = summary
1037 return data
1038
1039 @classmethod
1040 def from_data(cls, **data: Any) -> Self:
1041 """Create an instance from a dictionary."""
1042 return cls(**cls.coerce(**data))
1043
1044
1045 @dataclass(frozen=True, kw_only=True)
1046 class PythonOptions(PythonInputOptions): # type: ignore[override,unused-ignore]
1047 """Final options passed as template context."""
1048
1049 filters: list[tuple[re.Pattern, bool]] | Literal["public"] = field( # type: ignore[assignment]
1050 default_factory=lambda: [
1051 (re.compile(filtr.removeprefix("!")), filtr.startswith("!")) for filtr in _DEFAULT_FILTERS
1052 ],
1053 )
1054 """A list of filters, or `"public"`."""
1055
1056 summary: SummaryOption = field(default_factory=SummaryOption)
1057 """Whether to render summaries of modules, classes, functions (methods), attributes and type aliases."""
1058
1059 @classmethod
1060 def coerce(cls, **data: Any) -> MutableMapping[str, Any]:
1061 """Create an instance from a dictionary."""
1062 if "filters" in data and not isinstance(data["filters"], str):
1063 # Filters are `None` or a sequence of strings (tests use tuples).
1064 data["filters"] = [
1065 (re.compile(filtr.removeprefix("!")), filtr.startswith("!")) for filtr in data["filters"] or ()
1066 ]
1067 return super().coerce(**data)
1068
1069
1070 @dataclass(frozen=True, kw_only=True)
1071 class Inventory:
1072 """An inventory."""
1073
1074 url: Annotated[
1075 str,
1076 _Field(
1077 parent="inventories",
1078 description="The URL of the inventory.",
1079 ),
1080 ]
1081
1082 base_url: Annotated[
1083 str | None,
1084 _Field(
1085 parent="inventories",
1086 description="The base URL of the inventory.",
1087 ),
1088 ] = None
1089
1090 domains: Annotated[
1091 list[str],
1092 _Field(
1093 parent="inventories",
1094 description="The domains to load from the inventory.",
1095 ),
1096 ] = field(default_factory=lambda: ["py"])
1097
1098 @property
1099 def _config(self) -> dict[str, Any]:
1100 return {"base_url": self.base_url, "domains": self.domains}
1101
1102
1103 @dataclass(frozen=True, kw_only=True)
1104 class PythonInputConfig:
1105 """Python handler configuration."""
1106
1107 inventories: Annotated[
1108 list[str | Inventory],
1109 _Field(description="The inventories to load."),
1110 ] = field(default_factory=list)
1111
1112 paths: Annotated[
1113 list[str],
1114 _Field(description="The paths in which to search for Python packages."),
1115 ] = field(default_factory=lambda: ["."])
1116
1117 load_external_modules: Annotated[
1118 bool | None,
1119 _Field(description="Whether to always load external modules/packages."),
1120 ] = None
1121
1122 options: Annotated[
1123 PythonInputOptions,
1124 _Field(description="Configuration options for collecting and rendering objects."),
1125 ] = field(default_factory=PythonInputOptions)
1126
1127 locale: Annotated[
1128 str | None,
1129 _Field(
1130 description="Deprecated. Use mkdocstrings' own `locale` setting instead. The locale to use when translating template strings.",
1131 ),
1132 ] = None
1133
1134 @classmethod
1135 def coerce(cls, **data: Any) -> MutableMapping[str, Any]:
1136 """Coerce data."""
1137 return data
1138
1139 @classmethod
1140 def from_data(cls, **data: Any) -> Self:
1141 """Create an instance from a dictionary."""
1142 return cls(**cls.coerce(**data))
1143
1144
1145 @dataclass(frozen=True, kw_only=True)
1146 class PythonConfig(PythonInputConfig): # type: ignore[override,unused-ignore]
1147 """Python handler configuration."""
1148
1149 inventories: Annotated[
1150 list[Inventory],
1151 _Field(description="The object inventories to load."),
1152 ] = field(default_factory=list) # type: ignore[assignment]
1153
1154 options: Annotated[
1155 dict[str, Any],
1156 _Field(description="Configuration options for collecting and rendering objects."),
1157 ] = field(default_factory=dict) # type: ignore[assignment]
1158
1159 @classmethod
1160 def coerce(cls, **data: Any) -> MutableMapping[str, Any]:
1161 """Coerce data."""
1162 if "inventories" in data:
1163 data["inventories"] = [
1164 Inventory(url=inv) if isinstance(inv, str) else Inventory(**inv) for inv in data["inventories"]
1165 ]
1166 return data