SoFunction
Updated on 2025-03-10

The wonderful uses of docstring that cannot be ignored in Python

In Python programming, the readability and maintainability of the code are crucial. In addition to clear naming and well-structured code, good document strings (docstrings) are also a key tool to ensure that the code is easy to understand and use. docstring is a string used in Python to record the behavior of modules, classes, methods and functions, helping developers and users to quickly understand the functions and usage of the code. This article will introduce the use of docstring in detail, including how to write, format and apply it in different contexts.

What is docstring

docstring is a document string embedded in Python code that describes the functions of modules, classes, functions, or methods. It is usually placed inside a defined code block, immediately after the def or class declaration. docstring is a unique document tool in Python. It is not just annotation, but can also be automatically extracted and displayed through various tools.

Simple docstring

def greet(name):
    """Return a greeting message。
    parameter:
    name (str): The name of the greeted。
    return:
    str: Greeting message。
    """
    return f"Hello, {name}!"

In this example, the docstring of the greet function describes the purpose, parameters, and return values ​​of the function.

Basic syntax and format of docstring

Docstring is usually defined in triple quotations """ or "'', which allows document strings to be written across multiple lines. To ensure readability of docstring, certain formats and standards are often followed.

Multi-line docstring

def calculate_area(radius):
    """Calculate the area of ​​a circle。
    This is a multi-linedocstringExample。
    You can describe the behavior and precautions of functions in detail here。
    parameter:
    radius (float): The radius of the circle。
    return:
    float: Area of ​​a circle。
    """
    import math
    return  * radius ** 2

In this example, docstring not only describes the function's function, but also contains detailed information about the parameters and return values.

Standard format of docstring

The Python community widely uses several docstring format standards, the most common of which are Google style, NumPy style, and reStructuredText (reST) styles. These standards help developers write consistent and structured documents.

Google-style docstring

Google-style docstring uses a simple format and is divided into description, parameters and return values.

def add(x, y):
    """Calculate the sum of two numbers。
    Args:
        x (int or float): The first number。
        y (int or float): The second number。
    Returns:
        int or float: The sum of two numbers。
    """
    return x + y

NumPy style docstring

NumPy style docstring is more detailed and is usually used in scientific computing and data analysis libraries.

def multiply(a, b):
    """
     Calculate the product of two numbers.
     Parameters
     ----------
     a : int or float
         The first number.
     b : int or float
         The second number.
     Returns
     --------
     int or float
         The product of two numbers.
     """
    return a * b

reStructuredText(reST) style docstring

ReST-style docstring is usually used with document generation tools such as Sphinx, supporting rich formatting options.

def divide(x, y):
    """
     Calculate the quotient of two numbers.
     :param x: Divided.
     :type x: int or float
     :param y: Divisor.
     :type y: int or float
     :return: commerce.
     :rtype: float
     :raises ZeroDivisionError: Thrown when the divisor is zero.
     """
    if y == 0:
        raise ZeroDivisionError("The divisor cannot be zero")
    return x / y

Application of docstring in different contexts

Module-level docstring

Module-level docstring is used to describe the purpose and content of the entire module, usually placed on top of the module.

"""
 math_operations module
 This module provides simple mathematical functions including addition, subtraction, multiplication and division.
 """
 
def add(x, y):
    """Computing the sum of two numbers."""
    return x + y
 
def subtract(x, y):
    """Calculate the difference between two numbers."""
    return x - y

Class-level docstring

Class-level docstring is used to describe the functions, usage of a class, and the main methods contained in the class.

class Calculator:
    """A simple calculator class.
     This class provides basic mathematical operations, including addition and subtraction.
     """
 
    def add(self, x, y):
        """Computing the sum of two numbers."""
        return x + y
 
    def subtract(self, x, y):
        """Calculate the difference between two numbers."""
        return x - y

Function and method level docstring

Function and method-level docstring are the most common forms used to describe functions, parameters, return values, and exception handling of functions or methods.

def multiply(x, y):
    """Calculate the product of two numbers。
    parameter:
    x (int or float): The first number。
    y (int or float): The second number。
    return:
    int or float: The product of two numbers。
    """
    return x * y

How to extract and use docstring

Python has built-in help() function and __doc__ attribute, which can easily extract docstring. docstring can also be used to automatically generate documents, and is used with tools such as Sphinx.

Use the help() function to view docstring

def subtract(x, y):
    """Calculate the difference between two numbers."""
    return x - y
 
help(subtract)

Output:

Help on function subtract in module __main__:
 
subtract(x, y)
Calculate the difference between two numbers.

Use the __doc__ attribute

def divide(x, y):
    """Calculate the quotient of two numbers."""
    return x / y
 
print(divide.__doc__)

Output:

Calculate the quotient of two numbers.

Best practices for docstring

Concise and clear: docstring should describe the function of the code clearly and concisely, and should not be too verbose.

Cover all important information: including function functions, parameters, return values, exceptions, etc.

Follow format criteria: Choose the appropriate format criteria, such as Google style, NumPy style, or reST style, and be consistent throughout the project.

Avoid duplication with code: docstring should supplement the code's understanding, rather than repeating the code content.

Docstring for comprehensive application

def calculate_statistics(data):
    """Calculate the basic statistics of a given dataset。
    This function returns the average value of the dataset、Median and standard deviation。
    parameter:
    data (list of float): A list of values。
    return:
    dict: Include'average','median'and'std_dev'Dictionary of keys,Corresponding to averages、Median and standard deviation。
    abnormal:
    ValueError: Thrown when the dataset is empty。
    """
    if not data:
        raise ValueError("The dataset cannot be empty")
 
    average = sum(data) / len(data)
    median = sorted(data)[len(data) // 2]
    variance = sum((x - average) ** 2 for x in data) / len(data)
    std_dev = variance ** 0.5
 
    return {"average": average, "median": median, "std_dev": std_dev}

In this example, docstring describes the functions, parameters, return values, and possible exceptions of the function.

Summarize

This article discusses in detail how to use docstring in Python and its importance in improving code readability and maintainability. With specific examples, we describe how to write clear and concise docstrings in modules, classes, functions, and methods, and how to organize document content using different format standards such as Google, NumPy, and reST. It also shows how to extract and view docstring using Python built-in tools and discusses best practices for writing docstring. Mastering these techniques will help you create code with your own manual, making Python projects easier to understand and maintain.

This is the end of this article about the magical uses of docstring in Python that cannot be ignored. For more related Python docstring content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!