Your First Steps in Python: A Beginner to Intermediate Guide

Docstrings: Documenting Your Functions

Section 7

Functions: Reusable Blocks of Code

Your First Steps in Python: A Beginner to Intermediate GuideFunctions: Reusable Blocks of Code

As you write more Python code, especially functions, it's crucial to document them. This isn't just for others who might read your code; it's for your future self too! Good documentation makes your code understandable, maintainable, and easier to use. The primary way to document your functions in Python is through docstrings.

A docstring is a string literal that appears as the first statement in a module, function, class, or method definition. It's enclosed in triple quotes (either ''' or """). Think of it as a detailed explanation of what your function does, its parameters, and what it returns.

def greet(name):
    """This function greets the person passed in as a parameter."""
    print(f"Hello, {name}!")

You can access a function's docstring using the __doc__ attribute or the help() function.

print(greet.__doc__)
help(greet)

While a simple one-line docstring is good, more complex functions benefit from a more detailed structure. Common conventions include describing the function's purpose, its arguments (parameters), and what it returns.

A standard format for docstrings is often adopted, making them predictable and easily parsable by documentation generation tools. Here's a common structure:

def add_numbers(num1, num2):
    """Adds two numbers and returns the result.

    Args:
        num1 (int or float): The first number.
        num2 (int or float): The second number.

    Returns:
        int or float: The sum of num1 and num2.
    """
    return num1 + num2
チャプターへ戻る