Docstring is a short form of documentation strings. These are string literals that are used within a particular program or a piece of code. As a comment, it is used to document or specify a line or block of code. We know that documentation is very important in software development. Docstrings are an easy way for programmers to write code that is readable to them as well as other programmers.
So when the code is sent from one department or environment to another, docstrings and comments are used to make programs more understandable. In this article, we will learn more about docstrings in Python programming.
Docstrings in Python
A docstring in Python is a way to provide an explanation along with functions, modules, and classes. They are documentation strings that are used as comments. These strings are not assigned to any variables. They are added below a function or module to describe what it does.
Docstrings always start with a capital letter and end with a full stop. It can be a single line or a multiline comment. You must write the first line as a brief description of the code. When there are multiple lines in the docstring, the second line must be a blank. This will separate the description from the lines following it.
Docstrings are declared using triple double quotes “”” just below the method or class definition. It is recommended that all functions are provided with a docstring.
These strings can be accessed using a __doc__ method of the object. You can also use the help function.
Take a look at this example of declaring and accessing a docstring in Python:
def myProgram(): """Demonstrate docstrings in Python.""" return None print("Print Docstring Using __doc__:") print(myProgram.__doc__) print("\nPrint Docstring Using help:") help(myProgram)
Print Docstring Using __doc__: Demonstrate docstrings in Python. Print Docstring Using help: Help on function myProgram in module __main__: myProgram() Demonstrate docstrings in Python.
One line Docstrings
These strings start and end on the same line. Triple double quotes are mentioned at the beginning and at the end of these strings.
def addtownumber(a, b): """Python program to add two numbers.""" print('Sum of two mumbers: ',a+b) print(addtownumber.__doc__)
Python program to add two numbers.
These docstrings span multiple lines. It starts with a brief description of the code. This is followed by a blank line. A more elaborate description is then written. Like one line docstrings, these also start and end with triple double-quotes.
def addtownumber(a, b): """ Python program to add two numbers. Take value in variables a and b. Print sum of a and b. """ # Take sum to two numers in variable summ summ = a+b # Now print sum of two variables print('Sum of two mumbers: ',summ) print(addtownumber.__doc__)
Python program to add two numbers. Take value in variables a and b. Print sum of a and b.
Docstring Best Practices
While trying to document a program or a piece of code, it is important to remember that code and the documentation must remain in the same file. This makes it easier for someone else to read and use the code. As modern documentation allows programmers to put the documentation within the code using docstrings.
But there are some practices that you have to follow to write efficient documentation. Initially, you must put the single line or multiline docstrings right after defining a class or a method. Ideally, a docstring must clearly explain what a module, function or class does. It explains how you can use the function or the class, not its internal working.
Moreover, in case of a docstring written for a function, it must ideally contain the following:
- The logic of the function
- Function arguments and the data types used
- The return values of the function and its data types
Some best practices for writing single line docstrings are as follows:
- You must always use triple quotes for single line docstrings. This way you can expand them easily later on
- There must not be a blank line before or after the docstring
- The opening and closing quotes must be on the same line
- It will always end in a period
- The strings must describe the effect of the function like a command. For example, “Return multiplied value”. It is must not provide a description such as “Multiplies the two variables and stores the output in another variable”
- It must not reiterate the method parameters and look like a signature of the method. The docstring must simply explain what the method does and its return type
Best practices for multiline docstrings are mentioned below:
- The summary line must start and end in one line. A blank line must separate it from the rest of the lines of the docstring
- All the lines of the docstring have the same indentation
- It is best to insert a blank line after the docstring that is used for a class
- For modules, docstrings list all the methods, classes and exceptions within it
- For classes, docstrings are used for describing the class methods and instance variables
Python Comments vs Docstrings
The differences between comments and docstrings are as follows:
A hash symbol (#) is used to mention the initiation of a comment
They are written between double or triple quotes
These are basically statements that are used for describing what a particular line of code means
These are special strings that are used for providing documentation in Python programs
There are only single-line comments. Multi-line comments can be inserted in programs using multiple single-line comments
There are single line and multiple line docstrings
Comments are ignored by interpreters and compilers in Python
Compilers and interpreters execute docstrings
Comments are not visible after the program has been executed
You can see the docstrings using the __doc__ attribute
Docstrings for the Built-in print() Function
The __doc__ attribute can be used along with the print() method to view the documentation of the method. The following code will be used:
Docstrings for Python Modules
The docstrings in Python modules are used for describing all the functions, objects, classes and exceptions that are available when a module is imported. A one-line summary is necessary for each. Before the import statements, these docstrings are placed at the top of the Python file.
Furthermore, these docstrings must contain the following also:
- A brief description of the module
- Description of the arguments and keywords
- Definition about exceptions
- Information about the optional arguments
In the case of the package docstrings, they must be positioned at the top of the __init__.py file. All the sub-packages and modules are listed using this docstring.
Let's look at the docstrings for the builtin module in Python called array.
import array print(array.__doc__)
This module defines an object type which can efficiently represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.
Docstrings for Python Functions
The docstrings used for functions must be written in a way that it describes the purpose of the function. It must also mention all the arguments used, function return types, exceptions that are raised and optional arguments. If the keyword arguments are a part of the interface, it must be mentioned using a docstring.
Let's look at the docstrings for the builtin module in Python called array.
Return the absolute value of the argument.
Docstrings for Python Classes
Docstrings for Python classes are used for specifying the usage. It must also highlight the instance variables and public functions. The constructor for the class must be specified for the __init__ method. The class may have subclasses and additional interfaces for these subclasses. All of these subclasses and interfaces must be mentioned in docstrings.
There may be a case where the class is a subclass of another class. Its characteristics may be inherited from the parent class. Here, the docstring must mention the differences between the two classes. Use programming terms such as override and extend while describing the class methods.
class myprograms: """ This is the class of mathematical operations Function name addnum: to add two numbers Function name subnum: to subtract two numbers """ def addnum(x,y): """ This program take two number and generate addition of two numbers """ summ = x+y print("Sum: ",summ) def subnum(): """ This program take two number and generate difference of two numbers """ subb = x-y print("Difference: ",subb) help(myprograms) # to Access Class docstring help(myprograms.addnum) # to Access Method's docstring
Help on class myprograms in module __main__: class myprograms(builtins.object) | This is the class of mathematical operations | Function name addnum: to add two numbers | Function name subnum: to subtract two numbers | | Methods defined here: | | addnum(x, y) | This program take two number | and generate addition of two numbers | | subnum() | This program take two number | and generate difference of two numbers | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) Help on function addnum in module __main__: addnum(x, y) This program take two number and generate addition of two numbers
Using the help() Function for Docstrings
The help() function is used for reading all the docstrings that are related to objects. These docstrings are printed out to the console.
The common docstring formats are as follows:
reST (reStructured text)
This is the official documentation standard of the Python programming language. It is based on easy to use markup syntax. It is part of the Docutils project of the Python Doc-SIG (Documentation Special Interest Group). It is a very lightweight markup language. reST docstrings can be easily processed by documentation processing software like Docutils.
It is very easy to read inside source codes.
This is the docstring format recommended by Google. The format specifies that you must always use three double quotes for mentioning docstrings. They must begin with a summary line that might end with a period or a question mark. The summary has to be followed by a blank line. The rest of the docstring will be continued in the subsequent lines.
The NumPy format is a format that is a combination of Google docstrings and the reST format.
Tools that auto-generate documentation from docstrings
There are many tools for automatically generating Python documentation from docstrings. They are as follows:
This is the most popular documentation generator. It uses reST for the docstrings. It produces the output as an HTML page. The output is available in other formats such as LaTex, plain text and ePub It works with Python 2 and 3.
The pdoc tool is a simple library and a command line tool. It works with Python 2 and 3. You can view the documentation of local packages by using the in-built HTTP server.
This tool works only with Python version 2 and is a successor of epydoc. It examines the syntax trees and parses the source code for functioning. It can pass the object model to Sphinx if you want. It was initially written for the Twisted project.
Documentation can be very useful while working in large and complicated software projects. Docstrings in Python makes it easier for programmers to include documentation. The different docstring formats and tools have unique features. Check out the official website of the Python language to use them more efficiently.