How to Comment Code in Python

Reading Time: 4 Minutes
Publication date:

How to Get the Current Date and Time in Python?

One way to obtain the current date and time in Python is by using the date class from the date module.

Python Comments

Comments in a program are parts of the code that are ignored by the interpreter or compiler. They are needed to:

  • Make the code more readable
  • Explain what the code does and why
  • Prevent parts of the code from executing during testing/debugging
  • Note what needs to be done/redone/removed

Overall, comments are meant to make the programmer’s life easier – they play no role for the computer. However, in some programming approaches, like Extreme Programming, it is believed that if the code needs comments, the code is bad.

In this article, you will learn how to write comments in Python 3, what Docstring and PEP are.

Comments in Python

Different programming languages have different syntax for comments. Often, it’s a double slash (//). In Python 3, comments in the code start with the “#” sign. For example:

# Code prints a line to the console "Hello, World!"
print("Hello, World!")

A comment can also be placed on the same line as code:

print("Hello, World!")  # The code prints a string to the console "Hello, World!"

Comments should be useful to the reader. For example, such a comment is not helpful:

# This code clearly does something
print("Hello, World!")

A good comment should explain or describe the code and its objectives. Some developers believe that comments should describe the programmer’s intentions. Generally, it is correct to understand comments as a kind of documentation for the code. If they are useless, they should be removed.

A part of the code can also be formatted as a comment to prevent it from being executed. This can be useful during code testing and debugging.

Suppose we need to comment the following code:

db_lp = sqlite3.connect('login_password.db')
cursor_db = db_lp.cursor()
sql_create = '''CREATE TABLE passwords(
login TEXT PRIMARY KEY,
password TEXT NOT NULL);'''
cursor_db.execute(sql_create)
db_lp.commit()
cursor_db.close()
db_lp.close()

It can be commented as follows:

db_lp = sqlite3.connect('login_password.db')  # Create database login_password
cursor_db = db_lp.cursor()  # Cursor class object for executing SQL queries
# SQL request to create a password table in the database
sql_create = '''CREATE TABLE passwords(
login TEXT PRIMARY KEY,
password TEXT NOT NULL);'''
cursor_db.execute(sql_create)  # Execute the query sql_create
db_lp.commit()  # Confirm changes
# Close Cursor and database
cursor_db.close()
db_lp.close()

Sometimes manually commenting Python code is inconvenient. To format a block of Python code as single-line comments, you can use hotkeys:

  • PyCharm: Ctrl + /
  • Visual Studio Code: Ctrl + / for line comment/uncomment, Shift + Alt + A for code block
  • Eclipse: Ctrl + / for line comment/uncomment, Ctrl + Shift + / for code block
  • Visual Studio: Ctrl + K then Ctrl + C to comment code block, Ctrl + K then Ctrl + U to uncomment code block

Docstring in Python

A Docstring is a string literal placed immediately after the declaration of a module, function, class, or other structures. It is a convenient way to document the code and can be accessed later. Docstring was introduced in Python in 2001 and is described in PEP 257.

What is PEP?

The development of the Python language follows a clearly regulated process of creating, discussing, selecting, and implementing documents called PEP (Python Enhancement Proposal). PEP contains proposals for the development of the language: implementing new features, changing existing ones, etc. One of the most well-known (and useful) PEP documents is PEP 8, which includes a collection of recommendations and conventions for writing code in Python. If you plan to write in Python, you should be familiar with this convention. There are quite a few rules, and there are special tools to follow them. You can find some useful tools below.

Let’s return to Docstring. A Docstring is the first instruction in the declaration of an object. Here is an example:

def function(x, y, z):
    """Docstring of this function"""
    def inner_function():
        """Docstring of the nested function"""

The syntax of a Docstring involves three quotation marks at the start and end. Apostrophes can also be used instead of quotation marks, and two or one character can be used. However, PEP 257 recommends using three quotation marks.

The Docstring of an object can be accessed using the __doc__ attribute:

def subtraction(a, b):
    """The function subtracts number b from number a"""
    return a - b

print(subtraction.__doc__)

Result: The function subtracts number b from number a.

The __doc__ attribute can be used to get information about Python’s built-in methods, such as print:

print(print.__doc__)

Output:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

String literals anywhere in the Python code can also serve as documentation. They will not be recognized by the Python byte-code compiler and will not be accessible during program execution via the __doc__ attribute. However, there are two additional types of Docstring that can be extracted from the code by software tools.

Additional Docstring

Additional Docstrings are string literals ignored by the Python compiler but recognized by the Docutils tool. They are placed immediately after the Docstring. Here is an example:

def function(arg):
    """This is the docstring of this function. It will be available via the property __doc__."""
    """
    This is additional docstring, it will be ignored by the compiler, but recognized by Docutils.
    """
    pass

Attribute Docstring

Attribute Docstrings are string literals that follow a simple assignment in a module, class, or __init__ method. For example:

def f(x):
    """This is the docstring of this function. It will be available via the property __doc__"""
    return x**2

f.a = 1
"""This is an attribute docstring for the attribute f.a of the function, it will be ignored by the compiler, but recognized by Docutils."""

The main recommendations of PEP 257 for using Docstring are:

  • Leave a blank line after each Docstring.
  • The Docstring of a script should represent the “proper use” message, which can be displayed to the user when the script is called with incorrect arguments. It should describe functionality, parameter syntax, environment variables, and files used.
  • The Docstring of a module should list the important objects it defines and provide a one-line description of each.
  • The Docstring of a function or method should describe behavior, arguments, returns, potential exceptions, and operational limitations.
  • The Docstring of a class should describe its methods, instance variables, and behavior.
  • The class constructor should have its own separate Docstring in the __init__ method.
  • If a class is derived and its behavior is primarily inherited from the base class, its Docstring should mention this and describe potential differences.

Useful Tools

In conclusion, here is a list of tools that will be helpful in working with PEP 8 and commentary in Python 3:

  • pycodestyle: Checks your code for PEP 8 compliance.
  • Black: Formats your code primarily according to PEP 8.
  • Doxygen, PyDoc, pdoc: Automatically generate documentation from Docstrings.

5 / 5. 1

Share:

Leave a comment