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.
Python code
18 linesdef 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
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
- Use reStructuredText docstrings (PEP 257) or NumPy docstrings if your project follows those conventions.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.