Python Docstring – Things You Must KNOW

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

How to Define Python Docstring?

Python docstring are surrounded with a pair of triple double quotes (“””). Let’s look at some examples of defining docstrings.

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.

        __init__(self, emp_id, emp_name)

    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
        """ = emp_id = emp_name

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

3. Python Module Docstring Example

Let’s say we have defined above function and class in 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 docstring value from a special attribute __doc__. Let’s see how to access docstring values defined above.

1. Accessing Python Function Docstring



Python Docstring Example Function
Python Docstring Example

2. Accessing Python Class and Method Docstrings





Python Class Method Docstring Example
Python Class and Methods Docstring Example

3. Accessing Python Module Docstring

We will have to import 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
$  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 one-liner 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."""

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 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 at 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 super class, 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 same as in the function definition.

Why You Should Follow Python Docstring Guidelines?

Python docstrings can be accessed with __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.