Commenting Tips

Commenting Tips #

As you write single lines of code or short blocks of code, it may be relatively easy to keep track of what the code is doing and why you wrote it. However, as you write larger programs, it becomes more and more difficult to keep all of your reasoning in your mind.

You can use comments to annotate code as you read it, which can be helpful for your understanding. Comments are also helpful in providing information not captured by the code, like in this case:

# Swap the values of x and y. Because assigning to a variable deletes its old
# value, create a temporary variable to hold one of the values.
temp = x
x = y
y = temp

If you were to just see the three lines of code above, it might be difficult to work out why the variable temp is being defined and used in this way. The comments above explain what these three lines accomplish.

Commenting blocks of code in this way is helpful for outlining the broad steps of what you are trying to accomplish in a program. For example, you may have a program that reads a filename, reads that contents of the file, processes the contents in some way, and writes the processed data to another file. While you may find that simply splitting these steps into blocks of code is helpful enough, commenting each block of code can provide more insight into your design, particularly if a block is complex.

When you write code for others to read (i.e., not to annotate code for yourself), you should try to focus comments on why you wrote the code rather than what the code does. A helpful rule of thumb is to assume that the reader knows more Python than you. It is acceptable to describe what the code is doing at a high level, as shown in the example above. If you find yourself explaining the details of how the code is accomplishing its goals, your comment is likely too deep in the weeds.