Python docstrings, format and examples

In this tutorial, we will discuss python docstrings, and learn about docstring format with examples.

What is docstring in Python?

Docstring is a string literal appears after the definition of modules, functions or classes. In other words, it is a description of the function, class or module.

Lets define a small function to calculate the cube of a number

def cube(num):
    '''Takes n as number and returns cube of the number'''
    return num * num * num

Here the string literal ”Takes n as number and returns cube of the number” after the function definition is the docstring.

The Python object __doc__ attribute

Doc string is stored in a special attribute __doc__ of object . So cube.___doc__ will print the document string.

print(cube.__doc__)

Output

Takes n as number and returns cube of the number

We can print the docstring of any function as shown below.

print(abs.___doc__)

Output

Return the absolute value of the argument.

Here we can see that the documentation of abs function is stored the __doc__ attribute.

Types of docstrings

Python docstrings can be:

  • One line docstrings
  • Multi line docstrings

One line docstrings

One line docstrings should fit in single line.

Conventions to write one line docstrings

1. Even though they are single line docstrings we should use triple quotes around these docstrings.

def square(x):
""" Find the square of a number, return the result"""

2. The opening and closing quotes should be in single line. So the below one-line docstring is wrong.

def square(x):
"""Find the square of a number, return the result
"""

3. There’s no blank line either before or after the docstring.

4. It should prescribe function effects as a command (Do this, return that).

Multi line docstrings

Multi-line docstrings consist of one summary line like a one line docstring. The summary line followed by a blank line and a more detailed description and it may be used by the auto-indexing tools. We should separate the summary line from the rest of the docstring using one blank line. We can place a summary line on the opening quotes line or the next line. Let’s see an example of multi-line docstring:

def find_product(x,y):
  """Find product of two numbers

  Args:
      x (int): First number
      y (int): Second number
  """ 

Or we can write the summary text in the next line after the opening quotes.

def find_product(x,y):
  """
  Find product of two numbers

  Args:
      x (int): First number
      y (int): Second number
  """ 

PEP 257 multiline docstring guidelines for various objects in Python as follows.

1.Docstrings for Python functions

Docstrings for Python function:

  • Should summarize its behaviour
  • Should document arguments(including optional arguments),return value(s),exceptions raised, side-effects and restrictions on when it can be called.
def find_sum(x,y):
  """Find sum of two numbers

  Args:
      x (int): First number
      y (int): Second number
  Returns:
      The sum of numbers
  """ 
  sum = x + y
  return sum

print(find_sum.__doc__)

Output

Find sum of two numbers

  Args:
      x (int): First number
      y (int): Second number
  Returns:
      The sum of numbers

2. Docstrings for Python Classes

Docstrings for Python class:

  • Should summarize its behaviour , list public methods and instance variables.
  • Should document class constructor __init___ method and individual methods using its own docstring.
  • It should list interfaces for sub classing
class Student:
 """
  Class to represent student
  
  Args:
      name (str) : Name of the student
      age (int) : Age of the student

  """
  def __init__(self,name,age):
    self.name = name
    self.age = age

print(Student.__doc__)

Output

  Class to represent student
  
  Args:
      name (str) : Name of the student
      age (int) : Age of the student

3. Docstrings for Python modules

Docstrings for Python modules :

  • Should list classes, exceptions and functions and any other objects exported by module with one-line summary of each.
import os
print(os.__doc__)

Output

OS routines for NT or Posix depending on what system we're on.

This exports:
  - all functions from posix or nt, e.g. unlink, stat, etc.
  - os.path is either posixpath or ntpath
  - os.name is either 'posix' or 'nt'
  - os.curdir is a string representing the current directory (always '.')
  - os.pardir is a string representing the parent directory (always '..')
  - os.sep is the (or a most common) pathname separator ('/' or '\\')
  - os.extsep is the extension separator (always '.')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join;).

4. Docstrings for script /runnable program

Docstrings of a script / runnable program:

  • Should be similar to “usage” message, printed when incorrect arguments or argument missing (or with a “-h” option, for “help”)
  • It should serve as a quick reference to all the functions and arguments.

Docstring formats

Python docstring can be written using different formats. Some common formats used for docstrings are

  • Google docstring
  • ReStructuredText
  • Numpydoc
  • Epytext

Google docstring format

Google has their own docstring for Python. It can be interpreted by Sphinx Napoleon plugin.

Example :

"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""

ReStructuredText

The reStructuredText (reST) format is one of the common docstring formats. The Sphinx uses reST to generate documentation. The JetBrains’s Pycharm and Pyment uses it as output docstring format.

Example :

"""
This is a reST style.

:param param1: this is a first param
:param param2: thisNumpydoc is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

Numpydoc

It is based on Google doc format and it supports Sphinx.

Example :

"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""

Epytext

Finally, epytext is a javadoc style docstring format. It is the base format for epidoc documentation generator.

Example:

"""
This is a javadoc style.

@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

Conclusion

In conclusion, we have discussed python docstrings, formats with examples. Hope you enjoyed reading this article.

Leave a Comment