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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay