Python Comments – 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 comments in Python. They provide useful information about the code to the developers.


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

We can add comments for variables, functions, and classes. They are used to provide the intended use of the part of the code. Let’s look at some examples of comments in Python.

1. Comment for Variables

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

data = "#123"  # this is comment, data contains # and that is not part of the comment.

2. Comments for Functions

# This function adds the two numbers
def add(x, y):
    return x+y
Python Comments
Python Comments

3. Comments for Class

# This class provides utility functions to work with Strings
class StringUtils:

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

Python Comment Block or Multiline Comment

Sometimes it’s not feasible to have the comment in a single line. In this case, we can create a comment block or split the comment into multiple lines. We 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) are 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 a 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 strings as multiline comments. According to this Guido’s 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 to why a string is present in the code without any use. So, it’s better to stick to the regular multiline comments using hash characters.


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 organization, 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

Python Comment Shortcut to Comment Out a Block

If you are working with Python IDE or Jupyter Notebook, you can use a shortcut to comment out a block of the code.

  • macOS Comment Shortcut – Select the lines you want to comment and press Command+/ and it will automatically add # at the start of each line to turn them into a comment block. If it’s a blank line, it will add # at the start of the line and you can write the comment.
  • Windows and Linux Comment Shortcut – Use Ctrl+/ as the shortcut to turn a code block into a comment.

Summary

  • Python commenting system is simple and always starts with #.
  • Python docstring is used 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 to the program.
  • Having a commenting policy in place is always a good idea when working with many team members.

What’s Next?

We referenced a lot of topics in this tutorial, you should read the following tutorials to get a further understanding of them.

References: