Comments and docstrings

Published

2023-08-01

Comments in code

Virtually all programming languages allow programmers to add comments to their code, and Python is no different. Comments are text within your code which is ignored by the Python interpreter.

Comments have many uses:

  • explanations as to why a portion of code was written the way it was,
  • reminders to the programmer, and
  • guideposts for others who might read your code.

Comments are an essential part of your code. In fact, it’s helpful to think of your comments as you do your code. By that, I mean that the comments you supply should be of value to the reader—even if that reader is you.

Some folks say that code should explain how, and comments should explain why. This is not always the case, but it’s a very good rule in general. But beware: good comments cannot make up for opaque or poorly-written code.

Python also has what are called docstrings. While these are not ignored by the Python interpreter, it’s OK for the purposes of this textbook to think of them that way.

Docstrings are used for:

  • providing identifying information,
  • indicating the purpose and correct use of your code, and
  • providing detailed information about the inputs to and output from functions.

That said, here are some forms and guidelines for comments and docstrings.

Inline and single-line comments

The simplest comment is an inline or single-line comment. Python uses the # (call it what you will—pound sign, hash sign, number sign, or octothorpe) to start a comment. Everything following the # on the same line will be ignored by the Python interpreter. Here are some examples:

# This is a single-line comment

foo = 'bar'  # This is an inline comment

Docstrings

Docstring is short for documentation string. These are somewhat different from comments. According to PEP 257

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.

Docstrings are not ignored by the Python interpreter, but for the purposes of this textbook you may think of them that way. Docstrings are delimited with triple quotation marks. Docstrings may be single lines, thus:

def square(n):
    """Return the square of n."""
    return n * n

or they may span multiple lines:

"""
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210, section Z
Homework 5
"""

It’s a good idea to include a docstring in every program file to explain who you are and what your code is intended to do.

"""
Distance converter
J. Jones

This is a simple program that
converts miles to kilometers.
We use the constant KM_PER_MILE
= 1.60934 for these calculations.
"""

Using comments as scaffolding

You may find it helpful to use comments as scaffolding for your code. This involves using temporary comments that serve as placeholders or outlines of your program. In computer science, a description of steps written in plain language embedded in code is known as pseudocode.

For example, if one were asked to write a program that prompts the user for two integers and then prints out the sum, one might sketch this out with comments, and then replace the comments with code. For example:

# Get first integer from user
# Get second integer from user
# Calculate the sum
# Display the result

and then, implementing the code one line at a time:

a = int(input('Please enter an integer: '))
# Get second integer from user
# Calculate the sum
# Display the result
a = int(input('Please enter an integer: '))
b = int(input('Please enter another integer: '))
# Calculate the sum
# Display the result
a = int(input('Please enter an integer: '))
b = int(input('Please enter another integer: '))
result = a + b
# Display the result
a = int(input('Please enter an integer: '))
b = int(input('Please enter another integer: '))
result = a + b
print(f'The sum of the two numbers is {result}')

This approach allows you to design your program initially without fussing with syntax or implementation details, and then, once you have the outline sketched out in comments, you can focus on the details one step at a time.

TODOs and reminders

While you are writing code it’s often helpful to leave notes for yourself (or others working on the same code). TODO is commonly used to indicate a part of your code which has been left unfinished. Many IDEs recognize TODO and can automatically generate a list of unfinished to-do items.

Avoid over-commenting

While it is good practice to include comments in your code, well-written code often does not require much by way of comments. Accordingly, it’s important not to over-comment your code. Here are some examples of over-commenting:

song.set_tempo(120)  # set tempo to 120 beats / minute  NO!

x = x + 1  # add one to x  NO!

# I wrote this code before I had any coffee  NO!
Note

It is often the case that code from textbooks or presented in lectures is over-commented. This is for pedagogical purposes and should be understood as such.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).