DEV Community

Cover image for Comments and Docstrings in Python
Mcvean Soans
Mcvean Soans

Posted on

Comments and Docstrings in Python

Comments in Python

As we have seen in a previous post Executing a Python Program, a comment is a line (or multiple lines) of code which do not execute when the program is run. The sole purpose of comments is to provide more information about the written code.

Many a times while writing programs, we tend to ignore documenting the steps. This causes an issue not only to others that might read our code in the future, but our future selves too. For example, let us take a look at the following snippets which contain the exact same code -

Snippet 1:

lst = [1,2,3,4,5]
for i in lst:
    print(i)
Enter fullscreen mode Exit fullscreen mode

Snippet 2:

lst = [1,2,3,4,5] # Creating a list
# Looping over each element in the list
for i in lst:
    print(i) # Printing each element
Enter fullscreen mode Exit fullscreen mode

As we can see from the above snippets, the difference in the quality of code varies significantly. Any person can understand the functionality of the code from the second snippet easily as compared to the first snippet. Hence, we can conclude that proper documentation of the code using comments is essential while developing any application.

Python has 2 types of comments:

Single line comments -

These comments begin with the hash (#) symbol and the entire line after the hash symbol is treated as a comment.

Multi line comments -

When we want to comment multiple lines of code, we can do it as follows

Method 1:

# This is the first comment
# This is the second comment
# This is the third comment
Enter fullscreen mode Exit fullscreen mode

Method 2:

"""
This is the first comment
This is the second comment
This is the third comment
"""
Enter fullscreen mode Exit fullscreen mode

Method 3:

'''
This is the first comment
This is the second comment
This is the third comment
'''
Enter fullscreen mode Exit fullscreen mode

Docstrings

As we have previously seen, multi-line comments are regular strings which have the ability to span multiple lines. If these strings are not assigned to a variable, then they are removed from the memory by the garbage collector. Hence, using """ (triple double quotes) and ''' (triple single quotes) are not recommended for comments by developers since they occupy memory and delays the complete execution of the program.

The strings enclose within """ or ''' are called documentation strings or docstrings. These are useful to create an API (Application Programming Interface) documentation file, that provides a description of various features of a software, language or a product.

API documentation is critical if developers intend to distribute their work. Bad or improper documentation may lead to other developers not understanding the complexity in code, and they may completely reject the code simply because it did not make sense!

Top comments (0)