Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

"""
like image 737
Alex44 Avatar asked Feb 04 '26 20:02

Alex44


2 Answers

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.

like image 106
Błażej Michalik Avatar answered Feb 07 '26 10:02

Błażej Michalik


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.

like image 45
Alex44 Avatar answered Feb 07 '26 10:02

Alex44



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!