简体   繁体   中英

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 (eg, 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.

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
        """

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM