Alex44
Alex44

Reputation: 3855

How to embed code examples into a docstring?

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-serif 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)

"""

Upvotes: 11

Views: 11393

Answers (2)

Alex44
Alex44

Reputation: 3855

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.

Upvotes: 5

Błażej Michalik
Błażej Michalik

Reputation: 5055

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.

Upvotes: 16

Related Questions