Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add code snippets to python docstring (not as doctest)?

I would like to provide code snippets to show-case how one could use a particular method or class in python. How can I do that?

In Java one could use <pre> ... </pre> to do so.

Doctest is the only way? As I look at the existing docstrings for typical packages (e.g., pandas, numpy, etc), I never see anything other than doctest which is intended to test the method and not just to format text as python code. So, if doctest is the only way, what would be the proper way of formatting a snippet of code to look like interactive python sessions? I don't want to write my code in an interactive session each time and then c+p it in my docstring. It doesn't seem to be right.

like image 635
Azim Avatar asked Nov 15 '25 16:11

Azim


1 Answers

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
        """
like image 141
fizzybear Avatar answered Nov 18 '25 05:11

fizzybear



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!