How to Document Python Functions with Google Style Docstrings

Document a Python function with a Google style docstring to describe arguments and return values clearly.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

18 lines
Python 3.9+
def calculate_rectangle_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle.

    Args:
        length (float): The length of the rectangle in meters.
        width (float): The width of the rectangle in meters.

    Returns:
        float: The area of the rectangle in square meters.
    """
    return length * width


if __name__ == "__main__":
    length = 5.0
    width = 3.0
    result = calculate_rectangle_area(length, width)
    print(f"Rectangle area: {result} m²")

Output

stdout
Rectangle area: 15.0 m²

How it works

The Google style docstring is recognized by tools like Sphinx and pydocstyle, making your codebase more maintainable. The triple-quoted string inside the function describes what the function does, and the special Args: and Returns: sections give precise information about each parameter and the return value. Type hints (float) add an extra layer of clarity. When you run the script, the if __name__ == "__main__": block executes only when the file is run directly, which is a common pattern for demonstrating usage.

Common mistakes

  • Forgetting to use triple quotes for the docstring, using a single-line comment instead.
  • Using inconsistent section labels like `params` or `return` instead of the standard `Args:` and `Returns:`.
  • Not matching parameter names in the docstring with actual function parameters.

Variations

  1. Use reStructuredText docstrings (PEP 257) or NumPy docstrings if your project follows those conventions.
  2. Add a `Raises:` section to document exceptions the function may raise.

Real-world use cases

  • Documenting function signatures in a shared library so teammates and external users can understand the API.
  • Auto-generating API documentation with Sphinx from source code for large projects.
  • Enforcing documentation style rules with linters like pydocstyle in CI pipelines.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.