Before we start learning about Comments and Docstring in Python and its concepts, we should setup our Python Integrated Development Environment (IDE) on our local machine. Read through the following articles to learn more about What is an IDE, Popular IDEs for Python and Python installation on your machine.
- What is an IDE
- Popular IDEs for Python
- Python 3 Installation on Ubuntu Linux
- Python 3 Installation on Windows
Introduction to Comments in Python
In Python programming, comments are text written in a program that are ignored by the compiler or interpreter. Comments allow developers to explain their code, making it easier for others (or themselves) to understand the purpose and functionality of specific sections. Writing comments is a best practice to improve the readability and maintainability of your code.
What are Comments in Program
Comments in Python are lines of text in a code file that are not executed. They exist to provide descriptions or explanations about how the code works.
When Python converts code into bytecode during execution, comments are ignored by the interpreter, which means they don’t affect program functionality.
Purpose of comments
Purpose of comments is to provide description of the written code. So that, after reading the comments another user can better understand the code, purpose and related context of the code and its related functionality and test case scenarios.
The main goal of comments is to make your code more understandable to others and youself. Comments provide:
- Context => Describe why a particular code was written and why this approach was taken.
- Clarity => Explain complex code or logic.
- Documentation => Help other developers quickly understand your code.
Best practices for write comments
When writing comments in Python, it’s essential to follow some key best practices:
- Be Short but Informative – Comments should be concise yet informative. Provide only the necessary information to avoid unnecessary verbosity.
- Be Precise and Clear – Avoid vague or ambiguous comments. Make sure comments directly explain the code they refer to.
- Avoid Redundancy – Comments should not repeat the information already clear from the code. Instead, they should offer insights that aren’t obvious.
- Relevance specific to written code – Focus on describing specific sections of the code that need explanation. Not every line requires a comment.
- Language-Specific Terminology – Use language-appropriate terminology when writing comments. For Python code, use Python-specific terms.
Program to understand comments in Python
This program is to understand the different scenarios for comments in Python. Step by step, we will understand this program in more detail.
print("Welcome to shbytes.com")
# This is the program to explain the comments in python
'This is also a comment written in single quotes directly in script'
print("This # is not a comment, but a string")
# This comment explain the multi-line comment in python
'This is the second line of multi-line comment'
'This is the third line of multi-line comment'
print("This line is printed after the multi-line comments")
Syntax for writing comments in Python
- Comments in Python starts with “#” Hash symbol
- After the “#” character, Python interpreter ignores everything till end of line
# This is the program to explain the comments in python
This line in code snippet is a comment, anything written in this line after hash, will be ignored by Python interpreter.
- But # character inside a string is treated as string, not comment
print("This # is not a comment, but a string")
“#” symbol in between the string (with double quotes or single quotes) will not create a comment.
- # is more generic to write comments in Python. But sometimes comments can also be written using single quotes.
'This is also a comment written in single quotes directly in script'
Types of comments in Python
There are three type of comments in Python:
- Single line comment – Single-line comments in Python begin with a # symbol. These comments span a single line and are used to describe what the code is doing.
# This is the program to explain the comments in python
'This is also a comment written in single quotes directly in script'
- Multi-line comments – In Python, multi-line comments are typically written as multiple single-line comments, where each line starts with “#” symbol itself.
# This comment explain the multi-line comment in python
'This is the second line of multi-line comment'
'This is the third line of multi-line comment'
print("This line is printed after the multi-line comments")
- Docstring – Docstring are special type of comments, which are used to describe and write documentation for the class, function, or module. Docstrings are written using triple double quotes “””.
Docstring in Python
- Docstring are documentation strings used to explain the purpose of modules, classes, and functions.
- Docstring occurs as the first statement in a module, function, class, or method definition.
- Docstring are written using triple double quotes “””.
- Unlike regular comments, Python processes docstrings, and they can be accessed pro-grammatically using the __doc__ attribute or the help() function.
Best Practices for Writing Docstring in Python
- Be Clear and Descriptive – Docstrings should precisely describe the functionality of the module, class, or function.
- Include Parameters and Return Values – If applicable, explain what parameters the function takes and what it returns.
- Optional but Recommended – While docstrings are optional, it’s a good practice to include them in complex codebases.
Program to understand Docstring in Python
Docstrings are particularly useful in writing self-documenting code. They also provide additional functionality, such as integration with testing frameworks like doctest.
This program is to understand the different scenarios for Docstring in Python. Step by step, we will understand this program in more detail
def docstring_function(x):
"""This a python program from Shbytes
to explain the Docstring in python.
Here,it takes in a number x,
returns the square of x"""
return x**2
# access docstring using __doc__ method
print(docstring_function.__doc__)
print("\n---------------------------------------------------\n")
# access docstring using help() function
help(docstring_function)
Declaring Docstring
- Docstring in Python are declared with “”” triple double quotes”””.
- Writing docstring for function, module or class is optional, but it is a good practice to always write docstring for function, module or class.
def docstring_function(x):
"""This a python program from Shbytes
to explain the Docstring in python.
Here,it takes in a number x,
returns the square of x"""
return x**2
In the above code, a Docstring using triple double quotes has been defined as a first statement for the function “docstring_function”. This Docstring is providing description about that the function.
Accessing Docstring
- Docstring can be accessed using __doc__ method of the object
# access docstring using __doc__ method
print(docstring_function.__doc__)
- Also, Docstring can be accessed using the help function
# access docstring using help() function
help(docstring_function)
Docstring for Class or Module
Now, we understand about usage of Docstring, declaration of Docstring and accessing Docstring. We used Docstring with a function definition. Let’s use Docstring with a Class or Module.
Program for Docstring with Class and Module
This program is to understand the different scenarios for Docstring with Class and Module (file). Step by step, we will understand this program in more detail.
"""docstring for file or module - This is the docstring module"""
class Shbytes:
"""docstring for class - this is the class Shbytes"""
def __init__(self, a):
"""docstring for __init__ - This is the initialize method"""
self.a = a
def display_values(self):
"""docstring for display_values - this method is used to display the values"""
print(self.a)
print("\n---------------------------------------------------\n")
# access docstring at module level
print(__doc__)
print("\n---------------------------------------------------\n")
# access docstring at class level
print(Shbytes.__doc__)
print("\n---------------------------------------------------\n")
# access docstring using class object
shbytes_class_object = Shbytes()
print(shbytes_class_object.__doc__)
print("\n---------------------------------------------------\n")
# access docstring at method level
print(display_values.__doc__)
Docstring with Module
Modules are nothing but a file in which Python code is written.
- Declaring Docstring with Module – In the above code, first line is Docstring for a Module
"""docstring for file or module - This is the docstring module"""
- Accessing Docstring with Module – Docstring with Modules are accessed using __doc__
# access docstring at module level
print(__doc__)
Docstring with Class
- Declaring Docstring with Class – Define a Class and its first statement in triple double quotes will be a Docstring.
class Shbytes:
"""docstring for class - this is the class Shbytes"""
- Accessing Docstring at Class
Docstring at Class is accessed using __doc__ method with Class name.
# access docstring at class level
print(Shbytes.__doc__)
Docstring of Class can also be accessed using __doc__ method with class object.
# access docstring using class object
shbytes_class_object = Shbytes()
print(shbytes_class_object.__doc__)
Docstring with init method
Docstring can be defined with any method include “__init__” method.
def __init__(self, a):
"""docstring for __init__ - This is the initialize method"""
self.a = a
Conclusion: Writing Effective Comments and Docstrings in Python
Understanding how to properly use comments and docstrings can significantly improve the readability and maintainability of your Python code. Following best practices ensures that your code is not only functional but also easy to understand for future collaborators or your future self.
For further Python programming concepts, you can explore Python Variables and Data Types and Python Operators to deepen your understanding of Python fundamentals.
Code snippets and programs related to Python comments and Docstring in Python, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
Q: What is the purpose of writing a docstring for a module in Python?
Docstring for a module provides an overview of the module’s purpose and functionality. It generally describes the module’s contents, such as classes, functions, and any important details or usage examples. This module documentation is important to understand the functionality and features of the module and how to use those features. Docstring should be the top line of the Module. Docstring For example:
"""
This module provides functions for mathematical operations
such as addition, subtraction, multiplication, and division.
"""
Q: What tools can be used to generate documentation from Python docstrings?
Many tools has been developed that helps to generate documentation from Python docstrings. Some of the tools are:
- Sphinx – Sphinx is a powerful tool used to convert reStructuredText like formatted docstrings into HTML, PDF, and other formats. It is very popular and widely used to create Python project documentation. Use the following command to install sphinx =>
pip install sphinx
- pydoc – Pydoc is a Python module that automatically generates Python documentation in text or HTML format. This generated documentation can be accessed via terminal or can be serve as a web page. Following command used to generate documentation =>
pydoc -w module_name
- Doxygen: Doxygen was originally designed for C++, but its functionality can be extended to generate Python documentation as well. This generates documentation from annotated source code.
- Epydoc: Eplydoc is a tool to generate API documentation for Python modules, based on their docstrings.
Q: How docstrings can be used for testing in Python?
Docstrings can be used for testing in Python through a feature called doctests. Doctests allow to embed test cases in the docstrings of functions, classes, or modules. Python’s doctest
module can run these test cases to very the functionality. Example of doctest test cases:
def add(a, b):
"""
Add two numbers and return the result.
Example:
>>> add(2, 3)
5
>>> add(-1, 1)
0
"""
return a + b
if __name__ == "__main__":
import doctest
doctest.testmod()
- Documentation and Testing Together – Docstrings and test cases together helps to maintain updated documentation with updated test cases.
- Easy to Write and Understand: Doctests and test cases are easy to write and are complement of each other.
Test Your Knowledge: Practice Quiz
Related Topics
- Understanding Scope in Python Programming (with Example Programs)In previous articles, we learned about following topics: Understanding Scope in Programming Generally, in the scope of a program, a variable can be declared only once with the same name. But, it’s possible to declare variables with the same name in different scopes within the same program. Changing the value of a variable within a…
- Understanding Number Datatype in Python: Decimal, Octal and Hexadecimal NumbersUnderstanding the Number Datatype in Python: A Comprehensive Overview Number datatype in Python is a combination of different number format classes like Integer, Float, and Complex. Python supports the Decimal, Octal decimal, and Hexadecimal number systems. Program – Integer Number datatype Output of the Integer Number datatype program: Note from the output: Exploring Float Number…
- Introduction to Variables in Python & Variable Data TypesWhat are Variables in Python In Python, variables act as references to reserved memory locations where actual values are stored. Each variable name points to a specific memory address that holds the assigned value. In this case: How Variable Memory Works When we define variables, like height = 175, Python allocates a specific memory location…
- What Are Comments and Docstring in Python (With Programs)?Before we start learning about Comments and Docstring in Python and its concepts, we should setup our Python Integrated Development Environment (IDE) on our local machine. Read through the following articles to learn more about What is an IDE, Popular IDEs for Python and Python installation on your machine. Introduction to Comments in Python In…