DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com on

6 2

Documenting python code using docstrings

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (2)

Collapse
 
molecula451 profile image
Paul

Excellent !!

Collapse
 
notsag profile image
Maxime Gaston

To go further, check sphinx and the wonderful autodoc extension

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay