Python Docstring

Python Docstring (Document String) is a string literal that is the first statement in a module, function, class, or method.


How to Write a Python Docstring?

Python docstring is surrounded by a pair of triple double-quotes (“””). Let’s look at some examples of writing docstrings in Python.


1. Python Function Docstring Example

def multiply(a, b):
    """This method multiplies the given two numbers.

    Input Arguments: a, b must be numbers.
    Returns: Multiplication of a and b.
    """
    return a * b

2. Python Class Docstring Example

class Employee:
    """Employee class is used to hold employee object data.

    Methods:
        __init__(self, emp_id, emp_name)
        print()
    """

    def __init__(self, emp_id, emp_name):
        """Employee Class Constructor to initialize the object.

        Input Arguments: emp_id must be int, emp_name must be str
        """
        self.id = emp_id
        self.name = emp_name

    def print(self):
        """This method prints the employee information in a user friendly way."""
        print(f'Employee[{self.id}, {self.name}]')

3. Python Module Docstring Example

Let’s say we have defined the above function and class in docstrings.py file. Every Python script is also a module. We can define this module docstring as:

"""
This module shows some examples of Python Docstrings

Classes: Employee
Functions: multiply(a, b)
"""

How to Access Python Docstrings?

We can access the docstring value from a special attribute __doc__. Let’s see how to access docstring values defined above.


1. Accessing Python Function Docstring

print(multiply.__doc__)

Output:

Python Docstring Example Function
Python Docstring Example

2. Accessing Python Class and Method Docstrings

print(Employee.__doc__)

print(Employee.__init__.__doc__)

print(Employee.print.__doc__)

Output:

Python Class Method Docstring Example
Python Class and Methods Docstring Example

3. Accessing Python Module Docstring

We will have to import the docstrings module. Then we can access its Docstring value using the __doc__ attribute. We have commented above print statements before importing the docstrings module to avoid executing the print() statements.

$  python ls
docstrings.py
$  python 
$  python python3.7
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import docstrings
>>> 
>>> docstrings.__doc__
'\nThis module shows some examples of Python Docstrings\n\nClasses: Employee\nFunctions: multiply(a, b)\n'
>>> 
>>> docstrings.Employee.__doc__
'Employee class is used to hold employee object data.\n\n    Methods:\n        __init__(self, emp_id, emp_name)\n        print()\n    '
>>> 
>>> 
>>> docstrings.multiply.__doc__
'This method multiplies the given two numbers.\n\n    Input Arguments: a, b must be numbers.\n    Returns: Multiplication of a and b.\n    '
>>> 
>>> 
>>> docstrings.Employee.print.__doc__
'This method prints the employee information in a user friendly way.'
>>> 
Python Module Docstring Example
Python Module Docstring

Python One-liner Docstring

  • When the python docstring is defined in a single line, it’s called a one-line docstring.
  • The opening quotes and closing quotes are on the same line.
  • There is no blank line before or after the docstring value.
  • The best practice is to end the docstring with a period.
  • It’s best suited for small utility functions where we don’t need to specify many things.
  • Provide meaningful docstring to specify the function details and the output. For example:
def reverse_str(s):
    """Reverses the input string and returns it."""
    pass

Python Multi-line Docstring

  • When the Docstring value spans into multiple lines, it’s called multi-line docstring.
  • The best practice for multi-line docstring is to start with a summary line, then a blank line followed by a more detailed explanation.
  • The summary line can be on the same line as the opening quotes or the next line.
  • The entire multi-line docstring is indented the same as the quotes in its first line.

Python Docstring Best Practices

  1. The docstring of a Python script should specify how to use it. It should be printed when the script is executed with missing or wrong parameters.
  2. Python module docstring should list all the classes, functions, exceptions, and dependencies on other modules.
  3. Python function docstring should specify the behavior, input arguments, return types, and exceptions. If there are specific restrictions when the function can be called, it should be specified in the function docstring.
  4. The docstring of a class should list all the methods and attributes. If it’s inheriting from a superclass, the details should be provided.
  5. If a class method is overriding the superclass method, it should be specified.
  6. Python is case-sensitive. So keep the function argument names exactly the same as in the function definition.

Python Docstring Format

There are no rules associated with the format of the docstring. But, following a specific style will make your code look good. There are two popular docstring formats.

1. Epytext format

This is very similar to javadoc style comments. It contains method description, params, return, and details about exceptions raised.

def multiply(a, b):
    """This method multiplies the given two numbers.

   @param a: this is the first param
   @param b: this is the second param
   @return: returns after multiplying a with b
   @raise TypeError: raised when any of the params is not a number
    """

    return a * b

2. reStructuredText (reST) format

This is a new style and it’s recommended in PEP-287. This style is used by Sphinx to generate documentation.

def multiply(a, b):
    """This method multiplies the given two numbers.

   :param a: this is the first param
   :param b: this is the second param
   :return: returns after multiplying a with b
   :raise TypeError: raised when any of the params is not a number
    """

    return a * b

PyCharm docstring shortcut

PyCharm IDE auto-generates docstring in reST format for methods, just type triple double-quotes after the method declaration and hit enter.

Since PyCharm IDE supports auto-generation of reST style docstring and it’s also recommended by PEP-287, you should write docstring in this format.

Why You Should Follow Python Docstring Guidelines?

Python docstrings can be accessed with the __doc__ attribute. It’s very easy to build a system to parse the docstring and generate documentation of the project modules, classes, and functions. That’s why you should follow the docstring guidelines laid out in PEP-257.


Can we use Docstring for Multiline Comment?

I have seen many instances where the docstring is abused to provide multiline comments. Python doesn’t support multiline comments. If you want the comment to spread into multiple lines, start each line with the hash character. Don’t Abuse Python Docstrings.

Summary

Python docstring provides useful information about the function, class, or module. We can access the docstring value with the __doc__ variable. We should use the reST format for writing docstring for methods.

What’s Next?

Resources