DocStrings are not the only way. If you are using Sphinx to generate documentation then you should read this.
Example
Here is something I want to talk about:: <-- Special syntax to mark code beginning
def my_fn(foo, bar=True): # Code itself
"""A really useful function.
Returns None
"""
Answer from fizzybear on Stack OverflowThere 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.
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.
Embedded file in a docstring
python - How do I insert highlight or code-block into Sphinx-style docstrings? - Stack Overflow
Example Code Within Docstrings
No More Python Docstring Despair: Highlight Them in VSCode!
I am currently creating documentation using Sphinx for a library I have created. However, I am struggling to find out the best way to include examples on how to use the functions within the docstring.
Basically I want include a code snippet, that will get picked up by Sphinx and then by rst2pdf, and formatted into a code block. However, when I search for python docstrings and code examples, I just get info on how to create them.
Is what I am doing possible? If so, what is the best way to deal with this.