7

How can I embed code into a docstring to tell Sphinx to format the code similar as it will be done in Markdown (different background colour, monospaced sans font)? For example to document a code usage example.

""" This is a module documentation

Use this module like this:

   res = aFunction(something, goes, in)
   print(res.avalue)

"""
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Alex44
  • 3,597
  • 7
  • 39
  • 56

2 Answers2

11

There are a few ways to do it. I think the most sensible in your case would be .. code-block::

""" This is a module documentation

Use this module like this:

.. code-block:: python

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

Notice the blank line between the directive and the code block - it must be there in order for the block to render properly.

Błażej Michalik
  • 4,474
  • 40
  • 55
4

Another way (see the comment of mzjn on this post) to get code highlighted is to end with two(!) colons at the line before the code:

""" This is a module documentation

Use this module like this::

   res = aFunction(something, goes, in)
   print(res.avalue)

"""

The :: does the trick.

Alex44
  • 3,597
  • 7
  • 39
  • 56
  • 1
    It will work, but the syntax highlighting has to be set inside project configuration (see [literal-blocks reference](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#literal-blocks)), or using [`highlight`](https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-highlight) directive. – Błażej Michalik Oct 20 '20 at 20:56