how to write docstrings in python

In Python, docstrings are used to document the purpose and usage of a module, class, method, or function.

There are two types of docstrings in Python:

  • Single-line docstrings
  • Multi-line docstrings

Single-line docstrings are enclosed in triple quotes on a single line, immediately preceding the class, function, or method definition:

main.py
def my_function(param1, param2):
    """This function does X and returns Y."""
    # Function implementation here
    return Y
127 chars
5 lines

Multi-line docstrings are used when more detailed documentation is needed. They are enclosed in triple quotes on multiple lines, with an extended summary, parameters, and return value (if applicable):

main.py
def my_function(param1, param2):
    """This function does X and returns Y.

    :param param1: description of param1
    :param param2: description of param2
    :return: description of return value
    """
    # Function implementation here
    return Y
256 chars
10 lines

Note that the format of multi-line docstrings is not enforced by the Python interpreter, but there are documentation tools like Sphinx that can parse and generate documentation based on them.

related categories

gistlibby LogSnag