autodoc2-docstring directive

One of the key features of autodoc2 is the ability to identify object docstrings and render them in the documentation, using a given parser.

The autodoc2-docstring directive is used to render a docstring. It takes a single argument, the fully qualified name of the object whose docstring should be rendered.

Using the :literal: option, the docstring will be rendered as a literal block.

  • the :literal-linenos: option can be used to enable line numbers for the literal block, based on the line number in the source document,

  • the :literal-lexer: option can be used to specify the lexer to use for syntax highlighting.

.. autodoc2-docstring:: autodoc2.sphinx.docstring._example
    :literal:
    :literal-linenos:
    :literal-lexer: markdown

creates:

231This is an example docstring, written in MyST.
232
233It has a code fence:
234
235```python
236a = "hallo"
237```
238
239and a table:
240
241| a | b | c |
242| - | - | - |
243| 1 | 2 | 3 |
244
245and, using the `fieldlist` extension, a field list:
246
247:param a: the first parameter
248:param b: the second parameter
249:return: the return value

Omitting the :literal: option will render the docstring as a nested syntax block.

  • the parser option can be used to specify the parser to use for the docstring, such as myst, rst or a the fully qualified name of a custom parser class, If not specified the docstring will be rendered using the current parser.

  • the :allowtitles: option can be used to allow the docstring to contain heading, and can be used if the autodoc2-docstring is at the top level of the document.

.. autodoc2-docstring:: autodoc2.sphinx.docstring._example
    :parser: myst
    :allowtitles:

creates:

This is an example docstring, written in MyST.

It has a code fence:

a = "hallo"

and a table:

a

b

c

1

2

3

and, using the fieldlist extension, a field list:

param a:

the first parameter

param b:

the second parameter

return:

the return value

Specifying the parser for auto-generated documentation

When auto-documenting source code, by default the docstring will be rendered using the current parser.

To list specific parsers for specific objects, you can use the autodoc2_docstring_parser_regexes configuration option.

autodoc2_docstring_parser_regexes = [
    (r"autodoc2\.sphinx\.docstring\._example", "myst"),
]

You can see this in action at autodoc2.sphinx.docstring._example()