Reading Time: 5 minutes

What is a Comment?

python-logo

In simple terms, a comment is an entry added to the source code to allow a deeper understanding of the logic behind why the code was written the way it was. In Python, the ‘#’ or pound symbol is required before every comment. This symbol allows the Python interpreter or compiler to ignore the pursuant text. 

Why are Comments Needed?

When working in a large codebase, a developer may need to refer back to the information in comments weeks or months later to ensure that they understand the code’s original purpose. This information is necessary for the original idea’s formal logic aspect and is an essential criterion when working with other developers on an extensive project. 

Developers who review and/or follow up to revise a code section often rely heavily on the comments to recognize and follow the original developer’s thought processes. In this way, successive developers can add, edit, or modify the annotation to adjust the understanding or reasoning of further updates if the code changes. 

Comment Conventions

The default Python library requires lines of code to be no longer than 79 characters. This provision is different for comments, which is 72 characters. If a comment stretches beyond the 72 character docstring limit, the dev should add a second line beginning with the ‘#’ symbol. More than one line is often needed to explain the reasoning behind how or why a developer wrote the code.

When a comment is added, it should be written in complete sentences. It should also concisely express a simple idea to limit the explanation’s focus only to the section of code requiring clarification.

Typically, a dev should capitalize the first word of a comment. If it is used as an identifier, the initial term should begin with a lowercase letter. 

Types of Comments in Python

Single Line Block Comments

A single line block comment is marked using the ‘#’ symbol at the beginning of a line. This means that all the characters after the # symbol on a given line are part of the comment. The comment ends when the line ends.

#!/usr/bin/python3

# this is a single line comment describing the command below
command

Inline Comments

The second type of single line block comment is an inline comment. Inline comments exist on the same line as a line of code. Typically, inline comments are separated by a minimum of two spaces from a statement noted in the PEP 8 Python style guide. Using a single space is frowned on and considered bad form. 

#!/usr/bin/python3

for x in[1, 2, 3]:  # This is an inline comment 

Multi-Line Comments

Python does not employ a specific feature that creates multi-line comments like in Java or the C language. However, this does not mean that we cannot make multi-line comments in Python. There are two main methods to create multiple comment lines in our code. 

Block Comment: We can string together several, single-line comments to create a block comment. 

#!/usr/bin/python3

# This is
# a multi-line
# comment.

for x in[1, 2, 3]:

We can also use a delimiter on each end of a comment to create a multi-line comment. A delimiter is three double-quote symbols (""") or three single-quote symbols (''') strung together on each end of the comment. As seen in the example below, the text after the beginning delimiter can be on the same line, but the delimiter that ends a multi-line comment should be on a line by itself. 

#!/usr/bin/python3

""" This is
a multi-line
comment as well!
"""

Documentation Strings

Python also has a built-in concept called documentation strings or docstrings. A docstring is a string literal that is indented and sits under a function and explains what it does. These docstrings describe a function, class, module, or method. This text is included as a comment below the module. They are a more logical and useful version of commenting

We must be aware of where we place comments in our code. If a comment string follows:

  • Too closely after a function
  • The definition of a class
  • At the beginning of a module

it is read as a docstring; Which in Python gives it an altogether different meaning. The code below provides an example of a docstring. Notice how the comment below the function result = a * b is indented? This helps better define a docstring.

#!/usr/bin/python3

def stuff(a, b): 
    result = a * b
    """
    Below, we define the sum
    of the result
    to use in function x
    """
    return result

Docstrings also help associate and generate documentation about an object when employing the __doc__ attribute in the Python built-in help() system or interactive help function.

There are two types of docstrings:

  • One-liner: A docstring sits on one line.
  • Multi-line: Docstrings are composed of a summary line similar to a one-liner, followed by a blank line. A more detailed description follows the blank line.

For docstrings, always open and close the comment using either the “triple double quotes” format or a “triple single quote” format.

Here is an example of a one-liner docstring. 

#!/usr/bin/python3

for x in[1, 2, 3]:
""" This is a general for loop syntax """ 

Below is an example of a multi-line docstring.

#!/usr/bin/python3
def cars(GM, Ford, Chevy):
      """ This denotes the type and year of cars 
      GM 1992-2021
      Ford 1992-2021
      Chevy 1992-2021
      """ 

What are the Differences Then?

So, what are the differences between docstrings and multi-line comments?

Docstrings are primarily used when describing a function or providing contextual hints. A docstring is indented and sits under a function, and explains what the function does. Comments themselves are not indented and do not provide any functionality other than providing helpful information for developers trying to understand the code logic. If we do not assign a docstring to a variable, it acts as a comment.

Best Practices for Comments

  1. Ensure comments are as short and descriptive as possible without losing context.
  2. Always use comments to describe the logic of the code, not how it works.
  3. Limit redundant comments. Do not use the same comments over and over again for similarly named functions. Using a better naming convention for functions solves this problem.

Conclusion

Comments are an integral part of every Python script or program. They describe the functionality, purpose, or expected output of a code block. Multiple types of comments can be used in almost any situation, increasing the clarity and detail in a code block. Additionally, docstrings can be used as comments or can generate documentation about an object in the Python interactive help system. Comments are an integral part of any codebase and should be utilized as often as needed. They are especially helpful when explaining the logic of why the code exists and the reasoning behind its presence. Think of it this way. If you write a code section and come back after six months and don’t understand what it does or why it was used, write a comment for it.

About the Author: David Singer

I am a g33k, Linux blogger, developer, student, and former Tech Writer for Liquidweb.com. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Latest Articles

How to Edit Your DNS Hosts File

Read Article

How to Edit Your DNS Hosts File

Read Article

Microsoft Exchange Server Security Update

Read Article

How to Monitor Your Server in WHM

Read Article

How to Monitor Your Server in WHM

Read Article