Learning Center
Python

Comments in Python 3

2 Apr 2025
Hostman Team
Hostman Team

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

  • Make the code more readable;
  • Explain what the code does and why;
  • Prevent parts of the code from executing during testing/execution;
  • Leave notes about things that need to be done/modified/removed.

Overall, comments are meant to make a programmer's life easier—they play no role for the computer. However, in some programming methodologies, such as extreme programming, it is believed that if code needs comments, then the code is poorly written.

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

Comments in Python
Copy link

Different programming languages use different syntax for comments. Often, it's a double slash (//). In Python 3, comments in the code start with the # symbol. For example:

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

You can also place a comment on the same line as the code:

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

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

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

A good comment should explain or describe the code and its purpose. Some developers believe that comments should describe the programmer’s intent. In general, it is best to think of comments as a form of code documentation. If they are not useful, they should be removed.

You can also use comments to disable parts of the code to prevent them from executing. This can be useful for 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()

The goal of commenting is to make this block of code understandable. For example, we can comment it like this:

db_lp = sqlite3.connect('login_password.db')  # Creating the login_password database
cursor_db = db_lp.cursor()  # Cursor object for executing SQL queries

# SQL query to create the "passwords" table in the database
sql_create = '''CREATE TABLE passwords(
login TEXT PRIMARY KEY,
password TEXT NOT NULL);'''

cursor_db.execute(sql_create)  # Executing the sql_create query
db_lp.commit()  # Committing changes

# Closing the Cursor and database
cursor_db.close()  
db_lp.close()

Manually commenting Python code can be inconvenient. To format a block of code as single-line comments, you can use keyboard shortcuts:

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

Docstring in Python
Copy link

A Docstring is a string literal placed immediately after the declaration of a module, function, class, or other structure. It is a convenient way to document code, making it accessible for reference. Docstrings were introduced in Python in 2001 and are described in PEP 257.

What is PEP?
Copy link

Python's development follows a structured process involving creating, discussing, selecting, and implementing PEP (Python Enhancement Proposal) documents. PEPs contain proposals for language development, including new features, modifications to existing ones, etc.

One of the most well-known and useful PEP documents is PEP 8, which outlines guidelines and conventions for writing Python code. If you plan to write in Python, familiarize yourself with these conventions. Since there are many rules, special tools exist to help enforce them. Some useful tools are listed below.

Now, back to Docstring. A Docstring is the first statement in an object's declaration. Here’s an example:

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

The syntax for a Docstring is three double quotes at the beginning and end. You can also use single quotes or fewer than three quotes, but PEP 257 recommends using three double quotes.

You can access an object’s Docstring using the __doc__ method:

def subtraction(a, b):     
    """Function subtracts b from a"""
    return a - b

print(subtraction.__doc__)

Output:

Function subtracts b from a

You can also use the __doc__ property to get information about built-in Python 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 placed anywhere in the Python code can also serve as documentation. The Python bytecode compiler will not recognize them, and they will not be accessible at runtime via __doc__. However, there are two additional types of Docstrings that can be extracted using documentation tools.

Additional Docstrings
Copy link

Additional Docstrings are string literals ignored by the Python compiler but recognized by Docutils tools. They are placed immediately after a Docstring. Example:

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

Attribute Docstrings
Copy link

Attribute Docstrings are string literals placed immediately after a simple assignment at the module, class, or __init__ method level. Example:

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

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

Here are the main PEP 257 guidelines for using docstrings:

  • Leave a blank line after all Docstrings.
  • The script's Docstring should serve as a "usage message," potentially displayed to the user if incorrect arguments are provided. It should describe functionality, parameter syntax, environment variables, and files used.
  • The module's Docstring should list important objects with a one-line explanation for each.
  • The function/method Docstring should describe behavior, arguments, return values, possible exceptions, and constraints.
  • The class Docstring should include methods, instance variables, and describe the class behavior.
  • The constructor (__init__) should have its own separate Docstring.
  • If a class is a subclass and mostly inherits behavior from a parent class, its documentation should mention this and describe any differences.

Useful Tools
Copy link

Here are some tools to help with PEP 8 and comments in Python 3:

  • pycodestyle — Checks if your code follows PEP 8.
  • Black — Formats code according to PEP 8 (mostly).
  • Doxygen, PyDoc, pdoc — Automatically generate documentation from Docstrings.