Python Comment

In this article, we will learn how to use proper comments in our code. There are many reasons for documenting your code, and every language provides its own syntax for doing so. While it is always best practice to try and craft your variables, statements and objects to be as self-documenting as possible, there is always a need to explain what a function does, or why it was designed in a specific way, especially when logic has a very specific use-case or complexity. Python provides several different methods to introduce comments into your logic. In this example, I will be describing the different types, including block and documentation strings. We will also review some best practices for using comments.

1. Block Comments

Block comments are single or multiple lines of text, preceded by a #. The Python interpreter ignores any text after the # character. For example:

1.1 Single-line

# This function prints Hello, followed by the name argument passed in.
def print_hello(name):
    print(f'Hello, {name}')

1.2 Multi-line

# This function reverses a string using an extended slice, using the syntax
# [start,stop,step] Providing no value for start and stop,
# and -1 for step indicates start at 0 index, stop at length of string, 
# and step backwards from
 end of string to beginning:
def reverse_string(string):
    reversed_string = string[::-1]
    return reversed_string

1.3 In-line

Inline comments are written the same way as single or multi-line. But instead of preceding a block of code, they are placed in the same line. The Python interpreter will read and execute the command, but ignore any text following the #.

print(math.sqrt(4)) #prints the square root of 4.

2. String literals

String literals, or strings that are not assigned to a variable, can also be used as comments. Any string surrounded by single or double quotes, not assigned, will be ignored by the Python interpreter. For example:

import math
'Example of a logarithmic function.'
"n: the numeric value."
"base: the logarithmic base."

3. Documentation Strings

Documentation strings can be used as a cleaner way to write multi-line comments. The syntax is similar to other languages, such as Java’s multi-line /* comments */. Multi-line comments using documentation strings (or docstrings, as they are often referred) begin and end with triple quotes “”” or triple single quotes: ‘ ‘ ‘:

Define a function that will
square each number in a list.
values = [1,2,3,4,5,6]

def square(value):
    return value ** 2

def map_values(func, values):
    return list(map(func, values))

While docstrings are a clean way of writing multi-line comments, their intended use is to be associated with functions, methods, or classes. Including the docstring after their definition adds the string to the __doc__ attribute. You can then print the docstring comments using: method_name.__doc__. For example, including triple single quotes after the map_values function definition allows you to use __doc__ to print the function documentation:

def square(value):
    return value ** 2

def map_values(func, values):

    Returns a new list of values by applying a transformation function
    to each value of the original list.

    :param func: The transformation function that will be called on each value in the array
    :param values: An array of numeric values
    :return: list of transformed numeric values
    return list(map(func, values))

Fig. 1: Python Comment Output.
Fig. 1: Python Comment Output.

You can also call the help() method to display the function documentation as help text:



Help on function map_values in module __main__:

map_values(func, values)
    Returns a new list of values by applying a transformation function
    to each value of the original list.
    :param func: The transformation function that will be called on each value in the array
    :param values: An array of numeric values
    :return: list of transformed numeric values

4. Best Practices

I use a few best practices when writing comments, to ensure they are easy to understand while not becoming overly verbose, which can clutter your code.

  • Keep comments short and to the point, describing only the parts of the code that need clarity or further description. This will help anyone who maintains your code skim over the logic quickly to gain a general understanding, while also highlighting more complex sections for further study.
  • Use inline comments sparingly, to provide better readability and not clutter your code.
  • Use comments to add pseudo-code to unfinished sections of your work. This helps you keep track of what’s left to complete and how it may be completed. Pseudo-code as comments is a great way to help you estimate the work effort that remains.
  • Add documentation strings to larger, multi-line methods that take more than 2 arguments. This is especially true for methods that reach out to APIs. It’s always good to document methods that take arguments required by external APIs, data sources, or integrations.
  • Don’t use comments to over-explain your code. If your comment becomes a paragraph describing how a method works, this may indicate unnecessary complexity in your logic. Large blocks of comments describing functions or methods are indicators of refactoring. For example, the method may need split because it is responsible for too many things.
  • Do use comments to document any side-effects caused by your functions or methods. While side effects should be kept to a minimum, they do happen. Including them in docstrings will help a maintainer trace your code better, and discover potential bugs quicker.

5. Conclusion

Comments are a great way to document your code, not only to help maintainers read and interpret your work, but to integrate help text or documentation in your functions, methods, or classes. Python provides a simple yet effective way to add these comments, using block or documentation strings. Knowing when to add comments, how often, and how much, will come with time and practice. Following best practices will allow you to become more efficient at writing and understanding your own code, and give you insight into where refactoring may be needed. It also allows other developers to understand and trace through your work faster, providing a better overall work experience with your team.

Using comments concisely and wisely means less time relearning complex areas of your code, less effort explaining your work to others on your team, and an easier time estimating work effort if refactoring or enhancements are needed.

Stephen Ferjanec

Stephen graduated from the University at Buffalo, with Bachelor's degrees in Finance and Information Systems. He has worked in the finance industry for over 20 years, developing software applications for accounting, budgeting and forecasting solutions. His most recent projects are developing web and mobile applications in the retail sector, where he is mainly involved with reporting projects using Spring technologies and Angular.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button