Documenting python code using docstrings

Kelvin Wangonya - Nov 12 '19 - - Dev Community

Until recently, I thought python docstrings were just an alternative way to write comments in the code. As I have since learnt, they can be quite useful in writing documentation right into the code. Here's what I mean:

# hello.py

class Hello:
    def __init__(self):
        """This is the Hello class init method. It doesn't really
        do anything in this code. I just included it here so I can write this
        long multi-line docstring."""
        pass

    def hello():
        'Simply prints hello world!'
        print("Hello World!")
Enter fullscreen mode Exit fullscreen mode

Above is a simple python script - hello.py. To see the documentation for that class, run the script in the interactive shell:

$ python3 -i hello.py

>>>
Enter fullscreen mode Exit fullscreen mode

Then, type help(Hello):

>>> help(Hello)
Enter fullscreen mode Exit fullscreen mode

A neatly formatted documentation for the class should be returned.

class Hello(builtins.object)
|  Methods defined here:
|
|  __init__(self)
|      This is the Hello class init method. It doesn't really
|      do anything in this code. I just included it here so I can write this
|      long multi-line docstring.
|
|  hello()
|      Simply prints hello world!
|
|  ----------------------------------------------------------------------
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player