Algorithms, Blockchain and Cloud

Using DocStrings in Python


Writing documentation is sometimes necessary if a project involves collaboration between programmers. APIs should be well documented. I know most programmers hate to do the documentation after a project is almost finished. Instead, they can write comments to APIs, functions, according to a well-defined format and these comments can be parsed into a nice readable API documentation. For example, in Java, you have the javadoc which processes the comments written in front of the method declaration.

In Python, it is even simpler, you place the comments right after the def using triple quote block and you can get the document string at run time by using attribute __doc__ or help function. The example is given below.

#!/usr/bin/env python
# https://helloacm.com

def Test(a, b):
    """
        Test(a, b)
        Input Two Integers
        Output the Sum
    """
    return a + b

print Test.__doc__
help(Test)

The output is given below.

        Test(a, b)
        Input Two Integers
        Output the Sum
    
Help on function Test in module __main__:

Test(a, b)
    Test(a, b)
    Input Two Integers
    Output the Sum

However, if Python can’t find the comments, if will simply output the following.

None
Help on function Test in module __main__:

Test(a, b)

–EOF (The Ultimate Computing & Technology Blog) —

244 words
Last Post: The Multithreading Bug in a C# Project
Next Post: Delphi IO Error 103

The Permanent URL is: Using DocStrings in Python (AMP Version)

Exit mobile version