Python Comments Guide – Multiline Comments, Best Practices

Comments are an integral part of any program. Every programming language provides a way to add comments. Python commenting system is very easy. In this guide, we will learn about Python comments.


How to Write Comments in Python?

  • Python comments start with the # character and extend to the end of the line.
  • We can start a comment from the start of the line, after some whitespaces or code.
  • If the hash character is present in a string literal, it’s part of the string.

Python Comments Examples

name = "Pankaj"  # employee name
id = 100  # employee id

data = "#123"  # this is comment, data contains # and that is not part of the comment.
  • Comments for Functions
# This function adds the two numbers
def add(x, y):
    return x+y
Python Comments
Python Comments
  • Comments for Class
# This class provides utility functions to work with Strings
class StringUtils:

    def reverse(s):
        return ''.join(reversed(s))

Python Multiline Comment

Sometimes it’s not feasible to have the comment in a single line. In this case, you can split the comment into multiple lines. You have to prefix every line with the hash (#) to write a multiline comment.

# This class provides utility functions to work with Strings
# 1. reverse(s): returns the reverse of the input string
# 2. print(s): prints the string representation of the input object
class StringUtils:

    def reverse(s):
        return ''.join(reversed(s))
    
    def print(s):
        print(s)
Python Multiline Comment
Python Multiline Comment

Using Python Docstring as Multiline Comment

Python documentation strings (Docstring) is used to provide documentation for functions, classes, and modules. They are defined between a pair of triple double quotes (“””). They must be defined just below the function or class declaration.

Let’s have a quick look at some examples of Python docstrings.

def foo():
    """The foo() function needs to be implemented.
    Currently, this function does nothing."""
    pass


class Data:
    """ This class is used to hold Data objects information."""

We can access the docstring of an entity using __doc__ attribute.

print(foo.__doc__)
print(Data.__doc__)
Python Docstrings
Python Docstrings

Is it good idea to use Docstring to specify long multiline comments?

Python docstrings purpose is to provide documentation. Sometimes you will notice that it’s misused to provide long comments. However, it’s not the recommended approach. If you want the comment to spread into multiple lines, just prefix every line with the hash character.


Python Multiline String as Multiline Comments

We can also use multiline string as multiline comments. According to Guido tweet, they generate no code.

'''
This function read employees data from the database
emp_id: employee id, should be int
returns employee object.
'''
def read_emp_from_db(emp_id):
    i = int(emp_id)
    '''code to read emp data
    using the employee unique id number'''
    pass

However, it can lead to issues with indentation. It’s also confusing as why a string is present in the code without any use. So, it’s better to stick to the regular multiline comments using hash character.


Python Commenting Best Practices

  • Always provide meaningful comments to specify the use of the entity.
  • It’s better to break the long comment into multiple lines.
  • Don’t be rude in the comments.
  • Keep the comments to the point. Nobody wants to read a novel in the code comments.
  • Avoid useless comments that don’t provide any useful information. Below are some examples of useless comments.
# count variable
count = 10

# foo() function
def foo():
    pass
  • Sometimes comments are unnecessary. Having the proper name of the entity itself is good enough. Let’s look at an example of this scenario.
# This function add two numbers
def foo(x, y):
    return x + y


# Better to have function defined as below. There is no use of comments.

def add_two_numbers(x, y):
    return x + y
  • It’s always a good idea to have a commenting system in place. When working with many team members and multiple projects in an organisation, using a commenting policy is recommended. For example, you can define a commenting policy like this:
# {Object Type} - {Usage}
# Data Object - stores the Data fetched from the database
data_obj = Data()


# {Function Short Description}
# {Input Arguments and their types}
# {Return object details}
# {Exception Details}

# This function adds all the elements in the sequence or iterable
# numbers: sequence or iterable, all the elements must be numbers
# Returns the sum of all the numbers in the sequence or iterable
# Throws ArithmeticError if any of the element is not a number


def add_numbers(numbers):
    sum_numbers = 0
    for num in numbers:
        sum_numbers += num
    return sum_numbers

Conclusion

  • Python commenting system is simple and always starts with #.
  • Python docstring are for documentation. You should not misuse it for multiline comments.
  • Start every line with the hash character for multiline comments.
  • Follow the best practices for adding comments in the program.
  • Having a commenting policy in place is always a good idea when working with many team members.

References: