DEV Community

loading...

Documenting python code using docstrings

Kinyanjui Wangonya
👨🏾‍💻
Originally published at wangonya.com on ・1 min read

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

Discussion (2)

Collapse
molecula451 profile image
Paul

Excellent !!

Collapse
notsag profile image
Maxime Gaston

To go further, check sphinx and the wonderful autodoc extension