Docstrings

Learn how to use docstrings in Python to document functions, classes, and modules effectively.

Loading...
Docstrings

Docstrings are string literals used to describe a module, function, class, or method. They help document the purpose and behavior of the code and are typically placed right after the declaration.

For example:

def square(n):
    '''Takes in a number n, returns the square of n'''
    return n**2

Here, the docstring:

'''Takes in a number n, returns the square of n'''

is a description of the function.


Accessing Docstrings

You can access a function's docstring using its __doc__ attribute.

For example:

def square(n):
    '''Takes in a number n, returns the square of n'''
    return n**2
 
print(square.__doc__) 

Output:

Takes in a number n, returns the square of n

You can also use the built-in help() function to get more detailed information:

help(square)

Output:

Help on function square in module __main__:
 
square(n)
    Takes in a number n, returns the square of n

Docstring Styles

Single-line Docstrings

For simple functions, use a single line that describes what the function does.

def greet(name):
    """Return a greeting message."""
    return f"Hello, {name}!"
 
def is_even(number):
    """Check if a number is even."""
    return number % 2 == 0

Multiline Docstrings

For more complex functions, use multiline docstrings with detailed information.

def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    
    This function takes two parameters representing the dimensions
    of a rectangle and returns the calculated area.
    
    Args:
        length (float): The length of the rectangle
        width (float): The width of the rectangle
    
    Returns:
        float: The area of the rectangle
        
    Example:
        calculate_area(5, 3)
        15
    """
    return length * width

Docstring Conventions

Python follows PEP 257 for docstring conventions:

  • Use triple double quotes: """ is preferred over '''
  • First line summary: Should be a brief, one-line summary
  • Blank line separation: Multiline docstrings should have a blank line after the summary
  • Imperative mood: Use imperative mood ("Return the result" not "Returns the result")

Example following PEP 257:

def process_data(data, format_type="json"):
    """Process input data and return formatted output.
    
    Take raw data and convert it to the specified format.
    Default format is JSON, but CSV and XML are also supported.
    
    Args:
        data (list): Raw data to be processed
        format_type (str): Output format ('json', 'csv', 'xml')
        
    Returns:
        str: Formatted data string
        
    Raises:
        ValueError: If format_type is not supported
    """
    # Function implementation here
    pass

👉 Next tutorial: Python Comments vs Docstrings

Support my work!