## Introduction

A **Python docstring** is a string that appears at the beginning of a function and serves as a **human-readable explanation** of a function’s purpose, behavior, and usage.

### Why Use Docstrings?

Docstrings provide several benefits that contribute to better code development:

**Clarity:**By describing a function’s purpose, expected inputs, and outputs, docstrings make your code easier to understand for both yourself and others.**Readability:**Well-structured docstrings improve the readability of your code, allowing developers to quickly grasp the essence of a function without delving into the implementation details.**Automated Documentation:**Tools like`pydoc`

and integrated development environments (IDEs) can extract and display docstrings as documentation, providing a valuable resource for users of your functions.**Consistency:**Following a consistent docstring format within your codebase helps maintain a unified documentation style, leading to a more professional and organized project.**Testing:**Docstrings can also serve as a guide for writing unit tests, ensuring that a function behaves as expected and continues to do so after code changes.

## Adding a Docstring to a Function

To add a docstring to a function, place a string immediately after the function definition. Any string that is placed as the first thing in a function is interpreted by Python as a docstring.

**Example:**

def calculate_rectangle_area(length, width): "This function calculates the area of a rectangle." if length < 0 or width < 0: raise ValueError("Length and width must be non-negative") return length * width

In the example above, `"This function calculates the area of a rectangle."`

is the docstring for `calculate_rectangle_area()`

. In this case, it’s a single-line string surrounded by double quotes `""`

, but the docstring can also be of other valid Python string formats.

Docstrings can be single-quoted strings, such as `'This function calculates the area of a rectangle'`

as well as multi-line strings.

Multi-line strings are written with either triple double-quotes `"""`

or triple single-quotes`'''`

to open and close the string. As with single-line strings, you can choose either double or single quotes, but must stick with the same type of quote character for both opening and closing.

Here is the function above, written with a multi-line docstring:

def calculate_rectangle_area(length, width): """ This function calculates the area of a rectangle. It works by multiplying the length and width. An exception is raised if either of the dimensions is negative. """ if length < 0 or width < 0: raise ValueError("Length and width must be non-negative") return length * width

The new line after the opening triple-quote and before the closing is optional, but makes the docstring nicer.

As you can suspect, multi-line docstrings allow for more flexibility when providing a larger amount of documentation for a function.

## Writing and Formatting Python Docstrings

You can put anything you’d like into a docstring, but there are some conventions and standard formats to guide you.

Docstrings of thoroughly documented functions may include a general function description, descriptions of each parameter, return value, exceptions raised, and an example of usage.

A common docstring format used is **reStructuredText** (**reST**).

**Example:**

def calculate_rectangle_area(length, width): """ Calculates the area of a rectangle. :param length: The length of the rectangle (non-negative). :type length: float :param width: The width of the rectangle (non-negative). :type width: float :return: The calculated area of the rectangle. :rtype: float :raises ValueError: If either `length` or `width` is negative. :Example: Calculate the area of a rectangle with length 5 and width 3: >>> calculate_rectangle_area(5, 3) 15.0 """ if length < 0 or width < 0: raise ValueError("Length and width must be non-negative") return length * width

It’s ultimately up to you to decide how much or little documentation to include and what format to use.

### Drawbacks of Docstrings

Even though docstrings provide many benefits, it’s important to take into consideration their drawbacks when deciding the extent to which to use them in your project.

These drawbacks include:

**Creation Effort:**Writing comprehensive and accurate docstrings requires additional time and effort during the initial development phase. This can lead to slower code production.**Maintenance Overhead:**Keeping docstrings up-to-date requires additional effort when changes are made to the function’s behavior, parameters, or return values. Inaccurate or outdated docstrings can lead to confusion and are often worse than having no documentation at all.**Duplication:**If multiple functions share similar functionality, duplicating docstrings can result in redundant documentation. This may lead to discrepancies if changes are not propagated to all instances.**Complexity Documentation:**For intricate or complex algorithms, docstrings might struggle to provide sufficient clarity and depth of understanding.

It’s important to note that while docstrings have their drawbacks, they are still a valuable tool for improving code documentation and maintainability.

### Accessing Python Docstrings

Python provides a built-in function called `help()`

that displays help text for a function based on its docstring. You can use it interactively in a Python shell.

**Example:**

help(calculate_rectangle_area)

**Output:**

Help on function calculate_rectangle_area in module __main__: calculate_rectangle_area(length, width) Calculates the area of a rectangle. :param length: The length of the rectangle (non-negative). :type length: float :param width: The width of the rectangle (non-negative). :type width: float :return: The calculated area of the rectangle. :rtype: float :raises ValueError: If either `length` or `width` is negative. :Example: Calculate the area of a rectangle with length 5 and width 3: >>> calculate_rectangle_area(5, 3) 15.0

A function’s raw docstring can be accessed using its `__doc__`

property.

**Example:**

print(calculate_rectangle_area.__doc__)

**Output:**

Calculates the area of a rectangle. :param length: The length of the rectangle (non-negative). :type length: float :param width: The width of the rectangle (non-negative). :type width: float :return: The calculated area of the rectangle. :rtype: float :raises ValueError: If either `length` or `width` is negative. :Example: Calculate the area of a rectangle with length 5 and width 3: >>> calculate_rectangle_area(5, 3) 15.0

Additionally, many integrated development environments (IDEs) offer features that allow you to view docstrings by hovering over function names or pressing specific keyboard shortcuts.

## Summary & Reference for Python Docstring

A Python docstring serves as a human-readable explanation of a function’s purpose, behavior, and usage.

To create a docstring, place a string immediately after function definition.

def calculate_rectangle_area(length, width): "This function calculates the area of a rectangle." return length * width

Docstrings can be multi-line strings, which are enclosed by triple double-quotes `"""`

or triple single-quotes `'''`

.

def calculate_rectangle_area(length, width): """ This function calculates the area of a rectangle. It works by multiplying the length and width. An exception is raised if either of the dimensions is negative. """ if length < 0 or width < 0: raise ValueError("Length and width must be non-negative") return length * width

You can put anything you’d like into a docstring, but there are some conventions and standard formats to guide you. A common format is reStructuredText (reST):

def calculate_rectangle_area(length, width): """ Calculates the area of a rectangle. :param length: The length of the rectangle (non-negative). :type length: float :param width: The width of the rectangle (non-negative). :type width: float :return: The calculated area of the rectangle. :rtype: float :raises ValueError: If either `length` or `width` is negative. :Example: Calculate the area of a rectangle with length 5 and width 3: >>> calculate_rectangle_area(5, 3) 15.0 """ return length * width

Use `help()`

to display help text for a function based on its docstring.

help(calculate_rectangle_area)

You can access a function’s raw docstring using the `__doc__`

property.

calculate_rectangle_area.__doc__