Create Python Comments the Right Way (r) (r)

Jan 6, 2023
An illustration symbolizing Python comments.

Comments are notes developers add to their code to explain the code's purpose and what it is expected to do. Interpreters and compilers that turn code into action ignore comments, but they're essential to managing the software project.

Let's take a look at the inner workings of commenting in Python.

Comments on Python

In accordance with the Python PEP 8 Style Guide There are several things to keep in mind while writing comments:

  • Commentaries should always contain short and precise sentences.
  • It's better to have no comments at all, rather than one that's difficult to understand or is inaccurate.
  • Comments should be updated regularly to reflect any changes to your code.
  • A lot of comments could be distracting, and lower the quality of code. Commentary isn't necessary when the intention of the code is clear.

In Python the line can be considered a comment when it begins with a # symbol. If the Python interpreter encounters the symbol # within your code it does not consider anything following that symbol and will not cause errors. There are two methods to define single-line comments that are inline or block comments.

Inline Commentaries

Inline comments give brief descriptions of simple operations and variables and can be written on the same page as the code statement

border is 10 + x # Create an the offset 10px.

The comments explains the role of the code in the same statement as the code.

Block Comments

Block comments serve to explain complex logic within the code. Block comments are written in Python are built in the same way as inline comments. The only different is that the block comments are written on a separate line:

import csv
 from itertools import groupby
 
 # Get a list of names in a sequence from the csv file
 with open('new-top-firstNames.csv') as f:
 file_csv = csv.reader(f)
 
 # Skip the header part: (sr, name, perc)
 header = next(file_csv)
 
 # Only name from (number, name, perc)
 persons = [ x[1] for x in file_csv]
 
 # Sort the list by first letter because 
 # The groupby function looks for sequential data. persons.sort(key=lambda x:x[0])
 data = groupby(persons, key=lambda x:x[0])
 
 # Get every name as a list 
 data_grouped = 
 for k, v in data:
 # Get data in the form 
 # 'A' : ["Anthony", "Alex"], "B" : ["Benjamin"]
 data_grouped[k] = list(v)

When using block comments, these comments are written above the code they're explaining. The Python PEP8 Style Guide dictates that a line of code must not be more than seventy-nine characters and inline comments often push lines over this length. That's why block comments are written to describe the code on separate lines.

Multi-Line Comments

Python doesn't natively support multi-line comments, which means it doesn't have a specific feature for defining the term. Despite this, comments spanning several lines are frequently employed.

It is possible to create an elaborate multi-lined comment from multiple single-line comment lines by prefacing each line with #:

# interpreter 
 # ignores
 # these lines

There is also the option of using multi-line strings syntax. In Python, you can define multi-line strings by enclosing the string in """, triple double quotes, or "'' triple single quotes:

 print("Multi-Line Comment")
 """
This
string is Multi line """ 

In the code above, the multi-line string does not get assigned to a variable, this makes it behave just like a post. At moment of execution, Python ignores the string, and it doesn't get included in the bytecode. The above code will produce the following output

Multi-Line Comments

Special Comment

In addition to creating code that is understandable, comments can also be used for specific purposes when using Python for example, like planning future code additions and generating documentation.

Python Docstring Comments

In Python, docstrings are comments on multiple lines that describe the best way to utilize a particular function or class. The documentation of your code will be enhanced by the addition of excellent docstrings. When working with a function or class and employing an inbuilt help(obj) function Docstrings could be beneficial for providing an overview on the subject.

Python PEP 257 is a way of declaring Docstrings in Python, shown below:

From collections, import namedtuplefrom collections import namedtuple namedtuple('Person", ['name' "age"))
def get_person(name and age; d=False):"""
Returns the namedtuple("name", "age") object. Also returns dict('name"', "age') if arg `d` is TrueArguments:
name - first name. Must be string
 age - the age of the person, which must be intthe d value to be returned as `dict` (default=False)
(default=False)"""
Thep = Person(name Age, name)
when d is false: Return p._asdict()
Return to p

The code in the previous example, the docstring provided details on how the associated function functions. When using a documentation generator like Sphinx the docstring could be used to offer those who are using your program an overview of how to make use of this technique.

A docstring defined just below the function or class signature could also be returned through help(), the inbuilt aid() function. Its function help() function takes the name of an object or function as an argument, and outputs the function's output docstrings. The example above shows how help(get_person) can be used to display docstrings related to the function. The get_person function. When you run the program above inside an interactive shell with the -i flag, you'll be able to observe how the docstring is going to be parsed by Python. Run the above code using python -i file.py.

Screenshot: Python docstring comments parsed in the terminal.
Python Docstring comments are parsed by Command-Line Interface.

Help help(get_person) function will return a docstring for your program. The result includes get_person(name, age, d=False), which is the signature of a function which Python creates automatically.

The get_person.__ Doc__ attribute may also be used to retrieve and modify docstrings programmatically. After adding "Some additional information" in the above example this message appears in the subsequent call at help(get_person). Still, it's unlikely that you'll need to modify docstrings in a dynamic manner during runtime, such as this.

TODO Comments

While creating code, there will be instances when you'll need to highlight certain sections or blocks to be used to improve. This is accomplished by TODO comments. TODO comments can be useful in the event that you are planning to make updates or changes to your code or when you want to inform the project's users or coworkers that certain sections of your code are still to be created.

Do you want to know what we did to increase our volume by more than 1000 per cent?

Join 20,000+ others who get our weekly newsletter with insider WordPress advice!

TODO comments shouldn't be written using pseudocodeit is enough to briefly explain the function of the unwritten code.

TODO comments and block-style single-line comments have a lot in common, and the sole distinction in them is the fact the fact that TODO comments have to begin with an TODO prefix.

# TODO Download serialized information in the CSV file. Perform calculations on the data Return to the user

It is important to remember that although many IDEs are able to highlight these comments to the programmers, the Python interpreter does not view TODO comments differently than block comments.

Best Practices When Writing Python Comments

There are many guidelines to be observed when writing commentaries for ensuring reliability and high quality. Here are some suggestions to write high-quality comments using Python.

Beware of the obvious

The comments that say the obvious don't add any value to your code, and should be avoided. Examples:

x = x + 4# multiply x by 4.

That comment isn't useful, because it simply explains the function of the code but doesn't explain why it's needed to be done. The comments should be able to articulate the "why" rather than the "what" part of the code they're describing.

A better way to write it, the example above might look like this:

x = x + 4 # increase the border's width

Keep Python Comments Short and Sweet

Be sure to keep your posts short and easy to understand. They should be written in standard prose, not pseudocode, and shouldn't replace the need to go through the code in order to gain a broad outline of the program's functionality. Insufficient detail or complicated statements don't make a programmers job any easier. Examples:

# return area by doing, Area of the Cylinder equals (2*PI*r*h) + (2*PI*r*r)
 def get_area(r,h) Return (2*3.14*r*h) + (2*3.14*r*r)

The previous comment contains more details than are necessary for the reader. Instead of specifying the core idea, commentaries should offer general information about the code. The comment could be written to read:

# return area of the cylinder get_area(r,h) Return (2*3.14*r*h) + (2*3.14*r*r)

Make sure you use identifiers with care

Identifiers are to be used with caution in comments. Changes in identifier names, or even cases can confuse the reader. Example:

# return class() after modifying argument
 def func(cls, arg):
 return cls(arg+5)
 

The previous comment refers to the classes and argument but neither are found in the code. The comment could be written to read:

# return cls() after modifying arg
 def func(cls, arg):
 return cls(arg+5)

DRY and WET

When you're writing code, you should adhere to the DRY (don't repeat your own) principle and avoid WET (write every single word over and over).

It is the same for comments. Do not use multiple sentences in your code to explain the source code and attempt to combine comments explaining the same code into a single comment. However, it's important to be cautious when joining comments. Inexperienced merging of multiple commentaries can cause a massive comments that are incompatible with style guides and is challenging for the user to understand.

Remember that comments should reduce the reading time of the code.

Function that performs the work do_something(y) // Work cannot be performed when y is higher than the max_limit, if y is greater than 400:print('doing x work')

In the above code the comments are unnecessarily fragmented, and can be merged into one comment.

# function that does the x operation if arg:y is lower than max_limit
def do_something(y) (if y in range(400):print('doing something')

Consistent Indentation

Ensure that comments are punctuated at the same point in the same way as the code that they're explaining. If not, they could make it difficult for you to understand.

For example, this comment is not indented or positioned correctly:

for i, in the range(2,20, 2) (# only even numbersif verify(i) (i):# I must be confirmed using verifiable()
verify()perform(x)

It can be rewritten according to:

# only even numbers
for i within the range(2,20 2,2) # I must be confirmed by verify()
If verify(i):perform(x)

Summary

Comments are an essential part of writing understandable code. The investment you make in creating a comment will be something that your next self or any other developers that need to enhance your code base -- will value. Commenting also allows you to gain deeper insights into your code.

In this course, you've learned more about comments within Python, including the various types of Python comments, the best times to use each of them, and the best practices to follow when creating them.

Writing good comments is an art that has to be studied and developed. To practice writing comments you can consider add comments to the previous projects you worked on. To get ideas and observe best practices being applied, check out well-documented Python projects available on the GitHub.

  • Easy setup and management in the My dashboard
  • 24/7 expert support
  • The top Google Cloud Platform hardware and network, that is powered by Kubernetes to ensure maximum capacity
  • A high-end Cloudflare integration to speed up and security
  • The global reach of the audience is enhanced by up to 35 data centers, and 275+ PoPs worldwide