Up to $100 off Dedicated Servers
Reading Time: 8 minutes

What is a Comment?

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 hash (#), number sign, or pound symbol is required before every inline 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. 

When Reading Your Own Code

As a Python developer, you may sometimes need to revisit old code, code that was written weeks or months ago. When you do, it can be challenging to remember your reasoning behind the coding decisions you made at the time. However, by adding Python comments, you can jog your memory and provide yourself with a helpful reminder of your original thought process. Having a clear understanding of what you wrote and why you wrote it the way that you did will make any future updates or improvements to the code easier. Your future self will thank you for writing good comments.

When Others Are Reading Your Code

When sharing your code with others, it's essential that they can understand it easily, even if they are not familiar with the project's overall purpose. Writing clear and concise Python comments is crucial in making this possible, as it can help others understand the code's logic. This is particularly useful when collaborating with other developers, as well as for future reference. Future developers tasked with updating your code are thanking you already for writing good comments.

Comment Conventions

Though the Python standard library requires lines of code to be no longer than 79 characters, the style guide for Python Code suggests line length of docstrings and comments should be limited to 72 characters. For comments that would stretch beyond the 72-character limit, consider adding an additional line beginning with the hash (#) symbol. For multi-line comments with multiple paragraphs, separate the paragraphs with a # on a line by itself.


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 comment is marked using the hash (#) symbol at the beginning of a line. This means that all the characters after the hash (#) 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 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 upon 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 you cannot make multi-line comments in Python.

You can string together several single-line comments to create a block comment.

#!/usr/bin/python3

# This is a multi-line comment. Each sentence in a multi-line
# comment (or, block comment") should begin with a capital letter
# and should end with a period.
#
# The Python style guide suggests all comments should be sentences
# that are easily read by second-language English readers.
#
# New paragraphs in a block comment should be separated by the "#"
# character on a line by itself.
#
# Although comments *can* exceed 72 characters (some interpreters
# allow comments to be of any line length), for improved readability
# and portability, comments should not exceed 72 characters.

for i in [1, 2, 3]:
    print(i)

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 describes what it does. These docstrings describe how a function, class, module, or method works.

Be aware of where you place comments in your 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.

#!/usr/bin/python3

def stuff(a, b): 
    result = a * b
    """
    Here, 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 single-line docstring used to summarize obvious cases.
  • Multi-line: Docstrings are composed of a summary line similar to a one-liner, followed by a blank line. A more detailed description may follow the blank line.

For docstrings, always open and close the comment using three double quotes format.

Here is an example of a one-liner docstring.

def greet(name):
    """Return a greeting for the given name with newlines."""
    return f"\nhello, {name}\n"

# The tradition of using "hello, world" in program examples
# became popularized in the 1970s by Dennis Kernigham.
print(greet("world"))

Here is an example of a multi-line docstring.

def total_cars(GM, Ford, Chevy):
    """
    This function calculates the total number of cars 
    from three different car manufacturers.

    Args:
        GM (int): The number of cars from GM.
        Ford (int): The number of cars from Ford.
        Chevy (int): The number of cars from Chevy.

    Returns:
        int: The total number of cars from all three brands.
    """

Differences Between Comments and Docstrings in Python

In Python, comments and docstrings serve different purposes. Docstrings are meant to document the code (i.e., describe what the code does, list inputs and outputs, etc.), and comments are meant to explain the code (i.e, provide institutional context, state assumptions, offer reasoning for code changes, etc.).

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.

When Writing Code for Yourself

Write comments that are clear and concise, and add value to your future self. Reference files or resources specific to your development environment.

# Most recent version of our output.csv specification is found at
# https://bit.ly/3mH5y5f4Zz

import csv
with open('input.csv', newline='', encoding='utf-8') as f:
[...]

Remind yourself of any deviations from your preferred coding style.

    ##  noteToSelf: I would normally use SCREAMING_SNAKE_CASE
    ##  for constants but need to remember this client prefers
    ##  lowerCamelCase

When Writing Code for Others

Write comments that are clear, concise, and add value to future developers.

# This code is based on the example from the Python documentation:
# https://docs.python.org/3/library/csv.html#csv.DictWriter

import csv

with open('output.csv', 'w', newline='') as csvfile:
[...]

Comment for others when fixing bugs.

## NOTE: Because of issues with a downstream consumer,
## we now have to sanitize all output, removing any null
## characters and any trailing spaces.
name = name.replace('\x00', '').rstrip()

Warn others of deviations from the norm.

# NOTE: Some function names deviate from Python's recommended
# naming conventions because LEGACY. Python conventions would prefer
# something like "total_financial" or "sum_financials" but legacy
# support for some FORTRAN from Plethos Wealth dictates otherwise.

def TOT_FINS(financials, external):
[...]

Comment Practices to Avoid

Don’t Be Mean

It can be tempting to express your frustration at a fellow developer or department by writing snarky comments. Don’t do this. Even though your comments aren’t typically rolled-up into bytecode or automatic documentation, code lingers, and people talk. It will get back to them.

Don’t do this.

def dotexas(income):
    # UGH! This original code was so bad, it's giving me a headache!
    # Whoever *cough*GERALD*cough* wrote this should be fired.
    taxes = 0.09*pay
[...]

Instead, try this.

def calc_tax(income):
    # Calculates the tax owed based on income and tax rates
    tax_rate = CITY_TAX*pay
[...]

Don’t Be Obscure

Just as your code should clearly show what it does, your comments should clearly explain the why and how of the code.

Don’t do this.

# This function will do some stuff for Bob
def func(some_var):
    stuff = some_var * 2
    return stuff

Instead, try this.

# Doubles the input number and returns the result
def double(number_to_double):
    result = number_to_double * 2
    return result

Don’t Be Sparse or Cluttered

It is good to avoid being overly wordy in the comments and also good to avoid leaving comments that will soon become outdated, but it’s crucial to provide enough in your comments so the code is easy to understand and maintain. Explain the purpose and functionality of the code, but don’t leave so many comments that the code becomes cluttered and difficult to read.

Don’t do this.

# This function takes an input list and returns a new list
# that only contains the even numbers in the original list.
# It uses a for loop to iterate over the input list, and
# checks each element to see if it is even using the modulus
# operator. If it is even, it appends it to a new list and
# returns the new list.

def even_list(input_list):
    output_list = []
    for element in input_list:
        if element % 2 == 0:
            output_list.append(element)
    return output_list

Instead, try this.

def even_list(input_list):
    # Initialize an empty list to hold the even numbers
    output_list = []
    # Iterate over the input list and save the even elements
    for element in input_list:
        if element % 2 == 0:
            output_list.append(element)
    return output_list

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.

Your next Python project deserves the best hosting options backed by support from the Most Helpful Humans in Hosting®. Consider Liquid Web’s Dedicated Servers for dedicated hardware, software installation flexibility, and available full management for the peace of mind you need for your environment. Contact the sales team today for more information.

FAQ

How do I comment faster in Python?

How do I comment out multiple lines of code in Python?

Do comments in PythonPuython slow down the performance of the code?

Should I comment on every line of code in Python?

Latest Articles

Mount ISO files via IPMI using a local file and the Java method

Read Article

How to use NextCloud — setup and features

Read Article

Use ChatGPT to diagnose and resolve server issues

Read Article

What is SDDC VMware?

Read Article

Best authentication practices for email senders

Read Article