MkDocStrings

github Show source on GitHub

Docstring section (powered by mkdocstrings).

Example: DocStrings

Jinja

{{ "mknodes.MkDocStrings" | MkDocStrings(show_if_no_docstring=True, heading_level=3) }}

Python

MkDocStrings(obj='mknodes.MkDocStrings', heading_level=3, show_if_no_docstring=True)

class MkDocStrings(mknode.MkNode)

Docstring section (powered by mkdocstrings).

<a id="mknodes.MkDocStrings"></a>

```python
class MkDocStrings(mknode.MkNode)
```

Docstring section (powered by mkdocstrings).
<p><a id="mknodes.MkDocStrings"></a></p>
<pre><code class="language-python">class MkDocStrings(mknode.MkNode)
</code></pre>
<p>Docstring section (powered by mkdocstrings).</p>
<a id="mknodes.MkDocStrings"></a>

```python
class MkDocStrings(mknode.MkNode)
```

Docstring section (powered by mkdocstrings).

class MkDocStrings(mknode.MkNode)

Name

Children

Inherits

MkNode
mknodes.basenodes.mknode
Base class for everything which can be expressed as Markup.

graph TD
  2323526077["_mkdocstrings.MkDocStrings"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  1359323199 --> 2323526077
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/_mkdocstrings/metadata.toml
[metadata]
icon = "mdi:api"
name = "MkDocStrings"
group = "documentation"

[requirements.plugin.mkdocstrings]
[requirements.package.mkdocstrings]
extras = "python"


[examples.docstrings]
title = "DocStrings"
jinja = """
{{ "mknodes.MkDocStrings" | MkDocStrings(show_if_no_docstring=True, heading_level=3) }}
"""

[output.markdown]
template = """
::: {{ node.obj_path }}
{% if node.options %}
    options:
{% for k, v in node.options.items() %}
      {{ k }}: {{ v | repr }}
{% endfor %}
{% endif %}
"""
mknodes.basenodes._mkdocstrings.MkDocStrings
 17class MkDocStrings(mknode.MkNode):
 18    """Docstring section (powered by mkdocstrings)."""
 19
 20    REQUIRED_PLUGINS = [resources.Plugin("mkdocstrings")]
 21    REQUIRED_PACKAGES = [resources.Package("mkdocstrings", extras=["python"])]
 22    OPTIONS_DEFAULT: dict[str, Any] = {}
 23    ICON = "material/api"
 24
 25    def __init__(
 26        self,
 27        obj: (
 28            types.ModuleType
 29            | griffe.Object
 30            | str
 31            | tuple[str, ...]
 32            | list[str]
 33            | os.PathLike[str]
 34            | type
 35            | Callable[..., Any]
 36        ),
 37        for_topmost: bool = True,
 38        allow_inspection: bool | None = None,
 39        show_bases: bool | None = None,
 40        show_source: bool | None = None,
 41        preload_modules: list[str] | None = None,
 42        heading_level: int | None = None,
 43        show_root_heading: bool | None = None,
 44        show_root_toc_entry: bool | None = None,
 45        show_root_full_path: bool | None = None,
 46        show_root_members_full_path: bool | None = None,
 47        show_object_full_path: bool | None = None,
 48        show_category_heading: bool | None = None,
 49        show_symbol_type_heading: bool | None = None,
 50        show_symbol_type_toc: bool | None = None,
 51        show_docstring_description: bool | None = None,
 52        inherited_members: bool | None = None,
 53        members: list[str] | None = None,
 54        members_order: Literal["alphabetical", "source"] | None = None,
 55        filters: list[str] | None = None,
 56        group_by_category: bool | None = None,
 57        show_submodules: bool | None = None,
 58        docstring_section_style: Literal["table", "list", "spacy"] | None = None,
 59        merge_init_into_class: bool | None = None,
 60        show_if_no_docstring: bool | None = None,
 61        annotations_path: Literal["brief", "source"] | None = None,
 62        line_length: int | None = None,
 63        show_signature: bool | None = None,
 64        show_signature_annotations: bool | None = None,
 65        signature_crossrefs: bool | None = None,
 66        separate_signature: bool | None = None,
 67        **kwargs: Any,
 68    ) -> None:
 69        """Docstring section.
 70
 71        Global options for DocStrings can be overridden by setting the keyword arguments
 72        to not-None.
 73
 74        Args:
 75            obj: What to show DocStrings for.
 76            for_topmost: If True, try to find the "shortest" path to given object by
 77                         checking whether it can also be found in a parent module.
 78            allow_inspection: Whether to allow inspecting modules when visiting
 79                              them is not possible
 80            show_bases: Show the base classes of a class.
 81            show_source: Show the source code of this object.
 82            preload_modules: List of modules to pre-load.
 83            heading_level: The initial heading level to use.
 84            show_root_heading: Show the heading of the object at the root of the
 85                               documentation tree (i.e. the object referenced by
 86                               the identifier after :::).
 87            show_root_toc_entry: If the root heading is not shown, at least
 88                                 add a ToC entry for it.
 89            show_root_full_path: Show the full Python path for the root
 90                                 object heading.
 91            show_root_members_full_path: Show the full Python path of the
 92                                         root members.
 93            show_object_full_path: Show the full Python path of every object.
 94            show_category_heading: When grouped by categories, show a heading
 95                                   for each category.
 96            show_symbol_type_heading: Show the symbol type in headings (e.g. mod,
 97                                      class, func and attr).
 98            show_symbol_type_toc: Show the symbol type in the Table of
 99                                  Contents (e.g. mod, class, func and attr).
100            show_docstring_description: Whether to show the description from DocStrings
101            inherited_members: Also show inherited members.
102            members: An explicit list of members to render.
103            members_order: The members ordering to use.
104            filters: A list of filters applied to filter objects based on their name.
105                     A filter starting with ! will exclude matching objects instead of
106                     including them. The members option takes precedence over filters
107                     (filters will still be applied recursively to lower members in the
108                     hierarchy).
109            group_by_category: Group the object's children by categories:
110                               attributes, classes, functions, and modules.
111            show_submodules: When rendering a module, show its submodules recursively.
112            docstring_section_style: The style used to render docstring sections.
113            merge_init_into_class: Whether to merge the __init__ method into
114                                   the class' signature and docstring.
115            show_if_no_docstring: Show the object heading even if it has no
116                                  docstring or children with docstrings.
117            annotations_path: The verbosity for annotations path
118            line_length: Maximum line length when formatting code/signatures.
119            show_signature: Show methods and functions signatures.
120            show_signature_annotations: Show the type annotations in methods
121                                        and functions signatures.
122            signature_crossrefs: Whether to render cross-references for type
123                                 annotations in signatures.
124            separate_signature: Whether to put the whole signature in a code
125                                block below the heading. If Black is installed,
126                                the signature is also formatted using it.
127            kwargs: Keyword arguments passed to super.
128        """
129        super().__init__(**kwargs)
130        self.obj = obj
131        self.for_topmost = for_topmost
132        opts = dict(
133            allow_inspection=allow_inspection,
134            show_bases=show_bases,
135            show_source=show_source,
136            preload_modules=preload_modules,
137            heading_level=heading_level,
138            show_root_heading=show_root_heading,
139            show_root_toc_entry=show_root_toc_entry,
140            show_root_full_path=show_root_full_path,
141            show_root_members_full_path=show_root_members_full_path,
142            show_object_full_path=show_object_full_path,
143            show_category_heading=show_category_heading,
144            show_symbol_type_heading=show_symbol_type_heading,
145            show_symbol_type_toc=show_symbol_type_toc,
146            show_docstring_description=show_docstring_description,
147            inherited_members=inherited_members,
148            members=members,
149            members_order=members_order,
150            filters=filters,
151            group_by_category=group_by_category,
152            show_submodules=show_submodules,
153            docstring_section_style=docstring_section_style,
154            merge_init_into_class=merge_init_into_class,
155            show_if_no_docstring=show_if_no_docstring,
156            annotations_path=annotations_path,
157            line_length=line_length,
158            show_signature=show_signature,
159            show_signature_annotations=show_signature_annotations,
160            signature_crossrefs=signature_crossrefs,
161            separate_signature=separate_signature,
162        )
163        opts = self.OPTIONS_DEFAULT.copy() | opts
164        self._options = {k: v for k, v in opts.items() if v is not None}
165
166    def __repr__(self) -> str:
167        option_kwargs = {k: v for k, v in self.options.items() if v is not None}
168        return reprhelpers.get_repr(self, obj=self.obj, **option_kwargs)
169
170    @property
171    def obj_path(self) -> str:
172        match self.obj:
173            case types.ModuleType():
174                return self.obj.__name__
175            case griffe.Object():
176                return self.obj.path
177            case Callable():
178                if not self.for_topmost:
179                    return f"{self.obj.__module__}.{self.obj.__qualname__}"
180                topmost_path = classhelpers.get_topmost_module_path(self.obj)
181                return f"{topmost_path}.{self.obj.__qualname__}"
182            case str():
183                return self.obj  # for setting a manual path
184            case tuple() | list():
185                return ".".join(self.obj)
186            case _:
187                raise TypeError(self.obj)
188
189    @property
190    def options(self) -> dict[str, Any]:
191        import mknodes as mk
192
193        # The default section style does not work well inside Annotations,
194        # so we switch to "list" when any parent is an MkAnnotation
195        # and no style is explicitely set.
196        opts = self._options.copy()
197        style = opts.get("docstring_section_style")
198        if not style and self.is_descendant_of(mk.MkAnnotations):
199            opts["docstring_section_style"] = "list"
200            opts["show_root_heading"] = True
201        return opts
202
203    def to_md_unprocessed(self) -> str:
204        md = f"::: {self.obj_path}\n"
205        if not self.options:
206            return md
207        option_lines = [f"      {k}: {v!r}" for k, v in self.options.items()]
208        option_text = "\n".join(option_lines)
209        return f"{md}    options:\n{option_text}\n"
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes
 93def create_section_for_nodes(
 94    nav: mk.MkNav,
 95    klasses: Sequence[type[mk.MkNode]],
 96) -> mk.MkTable:
 97    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
 98    for kls in klasses:
 99        tpl = "classpage_custom.jinja"
100        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101        nav += page
102        if kls.STATUS:
103            page.metadata.status = kls.STATUS
104        elif kls.JS_FILES:
105            page.metadata.status = "js"
106        elif kls.CSS:
107            page.metadata.status = "css"
108        page.created_by = create_section_for_nodes
109        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111        table.add_row((link, kls.__doc__, extensions))
112    return table
Resources
Resources(css=[],
          markdown_extensions={'admonition': {},
                               'pymdownx.details': {},
                               'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7ff77e88b060>,
                                                                           'name': 'mermaid'}]},
                               'pymdownx.tabbed': {},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: material/api
title: MkDocStrings