Commenting Python Code

Programming reflects your way of thinking in order to describe the single steps that you took to solve a problem using a computer. Commenting your code helps explain your thought process, and helps you and others to understand later on the intention of your code. This allows you to more easily find errors, to fix them, to improve the code later on, and to reuse it in other applications as well.

Commenting is important to all kinds of projects, no matter whether they are - small, medium, or rather large. It is an essential part of your workflow, and is seen as good practice for developers. Without comments, things can get confusing, real fast. In this article we will explain the various methods of commenting Python supports, and how it can be used to automatically create documentation for your code using the so-called module-level docstrings.

Good vs Bad Comments

As important as comments are, it's still possible to write bad comments. They should always be short, straight to the point, and add informative value.

For example, this is a rather useless comment:

b = 56                       # assigning to b a value of 56

The next example shows a more helpful comment, instead, and goes along with giving variables obvious names:

salestax10 = 1.10            # defining a sales tax of 10%
salestax20 = 1.20            # defining a sales tax of 20%

There are an infinite number of other scenarios that warrant comments. This is just one example. A good rule of thumb would be to add comments for any line of code (like a list comprehension) or section of code whose purpose isn't obvious. This is very subjective, and is actually a skill that needs to be learned.

Types of Comments

A comment in Python starts with the hash character, #, and extends to the end of the physical line. A hash character within a string value is not seen as a comment, though. To be precise, a comment can be written in three ways - entirely on its own line, next to a statement of code, and as a multi-line comment block.

In the following sections I'll describe each type of comment.

Single-Line Comments

Such a comment starts with a hash character (#), and is followed by text that contains further explanations.

# defining the post code
postCode = 75000

You can also write a comment next to a code statement. The next example shows that:

# define the general structure of the product with default values
product = {
    "productId": 0,          # product reference id, default: 0
    "description": "",       # item description, default: empty
    "categoryId": 0,         # item category, default: 0
    "price": 0.00            # price, default: 0.00
}

The Style Guide for Python Code (PEP8) recommends less than 79 characters per line. In practice, 70 or 72 characters per line are easier to read, and thus is recommended. If your comment is approaching or exceeding this length then you will want to spread it out over multiple lines.

Multi-Line Comments

As already mentioned above, an entire comment block is also understood by Python. These comments serve as in-line documentation for others reading your code, and explain things in more detail, usually.

Technically Python doesn't have explicit support for multi-line comments, so the following options are considered a workaround by some, but still work for the purpose of multi-line comments.

Version 1 combines single-line comments as follows:

# LinuxThingy version 1.6.5
#
# Parameters:
#
# -t (--text): show the text interface
# -h (--help): display this help

Version 2 is simpler than version 1. It's originally intended to be used for creating documentation (see more about this below), but it can also be used for multi-line comments.

"""
LinuxThingy version 1.6.5

Parameters:

-t (--text): show the text interface
-h (--help): display this help
"""

Note that the latter version needs to be enclosed in special quotation marks (""") to work, and not hash characters.

Common Practice

It is quite common to start a Python file with a few lines of comments. These lines state information regarding the project, the purpose of the file, the programmer who developed it or has worked on it, and the software license that is used for the code.

This snippet is taken from one of the examples I use for training purposes. The comment starts with the description, and is followed by the copyright notice with my name, and the year of publication of the code. Below you will see that the code is licensed under GNU Public License (GPL). In order to contact me my email address is added there too.

# -----------------------------------------------------------
# demonstrates how to write ms excel files using python-openpyxl
#
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email [email protected]
# -----------------------------------------------------------

Docstring Comments

Python has a built-in concept called docstrings, which is a great way to associate documentation you've written with Python modules, functions, classes, and methods. A docstring is added as a comment right below the function, module, or object head, and describes what the function, module, or object does. It is expected to follow these rules:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  • A docstring is either a single line, or a multi-line comment. In the latter case, the first line is a short description, and after the first line an empty line follows.

  • Begin the docstring with a capital letter, and end it with a period.

This is a basic example of what it looks like:

def add(value1, value2):
    """Calculate the sum of value1 and value2."""
    return value1 + value2

In the Python interactive help system, the docstring is then made available via the __doc__ attribute.

>>> print add.__doc__
Calculate the sum of value1 and value2.

There is a number of tools that auto-generate documentation from docstrings, such as Doxygen, PyDoc, pdoc, and the autodoc extension for Sphinx. We will explain to you how to work with them in a follow-up article.

Conclusion

Writing proper comments in your Python code is not that complicated, and you just need the power of endurance. It helps all of us that are trying to understand your code, including yourself for when you revisit your code at a later date. We hope that the advice we have given you here makes it easier for you to create better comments and documentation in your code.

Acknowledgements

The author would like to thank Zoleka Hofmann for her critical comments while preparing this article.

Last Updated: August 10th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Frank HofmannAuthor

IT developer, trainer, and author. Coauthor of the Debian Package Management Book (http://www.dpmb.org/).

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms