Adding comments to your program will help other programmers understand your work. Without comments, it can be difficult to understand other people’s code. This is why it’s important to know when to use comments vs. docstrings as a Python programmer.
Knowing when to use comments and how to use them can be confusing. Do you know the difference between a docstring and a string comment?
In this tutorial, we’ll cover best practices for writing comments in Python. We’ll also show you how to use docstrings and explain how they differ from ordinary comments. Hopefully we can demystify the process of documenting Python code.
By the end of this post, you should have a firm grasp of when to use comments vs. docstrings in Python.
Using Python Block Comments
Making comments in Python is done in a variety of ways. This can be a little confusing for beginners. Understanding the difference between block comments and string comments will bring some clarity to the situation.
In Python, most comments are written using block comments. Block comments are preceded by a # sign. Python will ignore these statements when the program runs. Use block comments to provide short, explanatory notes.
Example 1: How to write a Block Comment in Python
# this is a Python block comment
It’s also possible to write a comment at the end of a Python statement. These comments are called inline comments. Inline comments are great for explaining non-obvious code.
Example 2: Inline Comments in Python
offset = width + 1 # compensate for the screen border
Inline comments can be extremely useful, but it’s best to use them sparingly. Less is more is a good rule to follow here.
Using Python String Comments
Block comments only take up a single line. If you need a comment that spans multiple lines, you’ll need to use more block comments. If you have a really long comment, or need to comment out a block of code, you can use a string comment. String comments are written using quotation marks.
Example 3: How to write a String Comment in Python
"""
This is an example of a string comment.
String comments can be many lines long.
Python will ignore them when you run the program.
"""
With string comments, there’s no limit on how long your comment can be. But there is a need for caution. String comments can be mistaken for docstrings if you put them in the wrong place.
For example, a string comment following a function will be interpreted as a docstring. For this reason, some Python programmers don’t use string comments at all.
Is it wrong to use Python string comments?
Some programmers frown on using strings as Python comments. Because they can be confused with docstrings, some Python coders even argue it’s best to avoid them altogether.
But the official words is that using string comments is perfectly fine. Even Guido Van Rossum, the creator of Python, has okayed the technique.
When to Use Python Comments
Use comments to leave notes about the code for others, and for yourself. Comments have several uses, but they are generally made for the developers.
Unlike docstrings, comments will not be turned into documentation. There are no rules for writing comments, only guidelines. If you look around, you’ll find varying opinions about when and when not to make comments.
In general, most programmers will tell you that comments are necessary in the following cases:
- When you need to explain complex algorithms.
- If you want to leave a TODO or explanatory note about unfinished code.
- If you need to provide a warning.
- When you want to include optional code.
Here are some other tips to keep in mind when you’re making comments:
- Keep comments as short as possible.
- Always be respectful and helpful to others.
- Use comments to explain why a decision was made.
- Use comments to explain how something works.
What is a Python Docstring?
Docstrings stand for Documents Strings and they provide a way of documenting a Python program. Using a docstring, programs can provide a description of the functions, classes, and modules that other programmers might want to use.
Using docstrings, Python developers can provide a simple explanation of what a function or class is used for. Without such documentation, it would be very difficult—if not impossible—to learn new Python modules.
Docstrings can also be used to generate API’s (Application Programming Interfaces). API’s are used to send data across the web. To use an API, it’s necessary to consult the documentation and learn how it works. Docstrings make generating this documentation easier by allowing programs to include it directly in the code.
How to Use Docstrings in Python
Now that we’ve made a distinction between docstrings vs. comments in Python, let’s take a closer look at how docstrings work and how to use them.
How to declare a docstring: Create a new docstring using triple quotation marks. For this reason, docstrings can be confused with string comments.
How to Access a Docstring: Docstrings can be read using the __doc__ attribute.
What Should a Docstring Look Like?
Unlike comments, docstrings have some formal requirements. To begin with, every docstring begins with a short summary of the function or class it’s related to.
The summary should be clear and concise. It’s important that programmers immediately grasp what a function does. This, however, is sometimes easier said than done, but should always be the goal.
Further documentation can be provided below the summary, following a blank line. The details of the docstring should serve as a quick reference for functions and arguments.
Documenting Python Functions
When documenting functions in Python, be sure to include descriptions of the function’s parameters. Also, give a detailed explanation of the return value of the function, if it has one.
Example 4: How to document a function in Python
def get_neighbors(some_list, index):
"""Returns the neighbors of a given index in a list.
Parameters:
some_list (list): Any basic list.
index (int): Position of an item in some_list.
Returns:
neighbors (list): A list of the elements beside the index in some_list.
"""
neighbors = []
if index - 1 >= 0:
neighbors.append(some_list[index-1])
if index < len(some_list):
neighbors.append(some_list[index+1])
return neighbors
some_list = [8,7,"car","banana",10]
print(get_neighbors(some_list, 2))
Output
[7, 'banana']
Accessing a Document String in Python
To access a docstring in Python, use the __doc__ attribute. This is a special attribute that will retrieve the docstring of a Python function or class. We can use the __doc__ attribute to print a docstring from the command line.
Example 5: Accessing a docstring with the __doc__ attribute
print(get_neighbors.__doc__)
Output
Returns the neighbors of a given index in a list.
Parameters:
some_list (list): Any basic list.
index (int): Position of an item in some_list.
Returns:
neighbors (list): A list of the neighboring elements of the index in some_list.
Documenting a Python Class with Docstrings
When documenting classes in Python, it’s important to include a summary of what the class represents as well as an explanation of the classes’ attributes and methods.
Each method in the class will also require a docstring. Below, you’ll find an example of a blog post class. Python docstrings are used to provide a detailed description of the class and it’s methods.
Example 5: How to document a class in Python
class BlogPost:
"""
A generic blog post model.
...
Attributes
----------
author: str
who wrote the blog post
title: str
the title of the blog post
content: str
the body content of the blog post
Methods
----------
description():
Prints the author, title, and content of the blog post
"""
def __init__(self, author, title, content):
"""Constructs all the necessary attributes of the blog post object.
Parameters
----------
author: str
who wrote the blog post
title: str
the title of the blog post
content: str
the body content of the blog post
"""
self.author = author
self.title = title
self.content = content
def description(self):
"""Prints the author, title, and content of the blog post.
Returns
-------
None
"""
print(f'{self.author}\n{self.title}\n{self.content}')
Programmers differ when it comes to the styling choices used to write docstrings. With a little research, you can find many style guides. How you choose to format your docstring will depend on many factors, the least of which may be personal choice. Keep in mind who your documentation is aimed at.
Summary
Knowing when to use comments vs. docstrings in Python is crucial to building robust, complex programs. Learning how and when to make comments will not only aid you in collaborative efforts, it will also save you time.
Unlike string comments, docstrings are meant to be read by the public. They provide an insight into how to use functions, classes, and modules. This makes it easier for other programmers to learn how to use the module in their own projects.
A quick recap on comments vs docstrings:
- Use comments to explain how code works.
- Comments are great for leaving notes for people working on your program.
- Docstrings provide documentation about functions, classes, and modules.
- Use docstrings to teach other developers how to use your program.
Related Posts
- How to use Python read file functions to open text files.
- Using Python split() to split strings.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.