General
Python Docstring Writing Guide: Google, NumPy, and reST Formats
Table of contents
Why Docstrings Matter More Than You ThinkThe Big Three: Google, NumPy, and reSTStyle Comparison at a GlanceAutomating Docstring Quality: Syntax Validation and LintingPractical Tips for Effective DocstringsConclusionWhy Docstrings Matter More Than You Think
Docstrings are the first line of communication between your code and its users—whether those users are other developers, your future self, or automated documentation generators. A well-written docstring reduces onboarding time, prevents misuse of functions, and makes your codebase feel professional. Yet many Python projects neglect docstring quality, leading to inconsistent formats, vague descriptions, and broken documentation builds.
The good news? Python offers several widely accepted docstring conventions, each with its own strengths. In this guide, we'll break down the three most popular styles—Google, NumPy, and reStructuredText (reST)—and show you how to validate and improve your docstrings with the right tools.
The Big Three: Google, NumPy, and reST
Python's official documentation doesn't mandate a single docstring format, but three styles have emerged as de facto standards:
- Google Style: Favored for its readability and simplicity, especially in data science and machine learning projects.
- NumPy Style: Popular in scientific computing, with a structured format that integrates well with Sphinx.
- reStructuredText (reST) Style: The classic Sphinx-native format, offering maximum control over rendered documentation.
Let's explore each style in detail.
Google Style Docstrings
Google's style is beloved for its clean, human-friendly look. It uses section headers like
Args:, Returns:, and Raises: followed by indented bullet points for each parameter or return value.def fetch_data(url: str, timeout: int = 10) -> dict:
"""Fetch JSON data from a remote API.
Args:
url: The API endpoint to request.
timeout: Maximum wait time in seconds.
Returns:
A dictionary containing the parsed JSON response.
Raises:
ConnectionError: If the request fails due to network issues.
TimeoutError: If the request exceeds the given timeout.
"""
...Pros: Extremely readable, minimal syntax noise, easy to write by hand. Cons: Requires a blank line between sections, and parameter descriptions aren't tied to types as rigidly as in NumPy style.
NumPy Style Docstrings
NumPy's format is more structured, using underlined section headers and a dedicated
Parameters section where each parameter gets its own block with a name, type, and description.def compute_average(values: list[float]) -> float:
"""Compute the arithmetic mean of a list of numbers.
Parameters
----------
values : list of float
The numbers to average.
Returns
-------
float
The arithmetic mean of the input values.
"""
...NumPy style excels when you need to document types and defaults explicitly, making it a favorite in scientific Python libraries. However, it's slightly more verbose and less intuitive for beginners than Google style.
reStructuredText (reST) Style Docstrings
The reST style uses Sphinx directives like
:param name:, :type name:, and :returns: to describe parameters and return values. It's the most powerful for generating rich HTML/PDF documentation because it leverages Sphinx's full markup capabilities.def connect_to_database(host: str, port: int = 5432) -> Connection:
"""Establish a database connection.
:param host: The database server hostname.
:type host: str
:param port: The connection port.
:type port: int
:returns: A database connection object.
:rtype: Connection
:raises ConnectionError: If the connection cannot be established.
"""
...While highly flexible, reST docstrings can become cluttered with directives, and they're less pleasant to read in raw source code than Google or NumPy styles.
Style Comparison at a Glance
| Characteristic | Google Style | NumPy Style | reST Style |
|----------------|--------------|-------------|------------|
| Readability in raw code | Excellent | Very good | Moderate |
| Parameter documentation | Bullet list under
Args: | Structured block with type and description | :param and :type directives || Return value documentation | Bullet list under
Returns: | Structured block under Returns | :returns and :rtype directives || Sphinx integration | Good (with napoleon extension) | Good (with napoleon extension) | Native |
| Best for | Data science, web apps, general Python | Scientific computing, libraries | Projects already heavily using Sphinx |
Choose the style that matches your team's existing conventions or the ecosystem you're working in. The key is consistency—mixing styles within a project is worse than choosing any single one.
Automating Docstring Quality: Syntax Validation and Linting
Writing docstrings manually is only half the battle. To ensure they're correct, complete, and consistent, you need automated checks. Here are some tools that can help:
- pydocstyle: Checks that your docstrings exist, follow PEP 257 conventions, and match a selected style (via
--convention=google, numpy, or pep257). It's a great first line of defense.- flake8-docstrings: A flake8 plugin that runs pydocstyle checks as part of your normal linting workflow.
- darglint: Verifies that every function argument and return value is actually documented in the docstring, catching missing parameter descriptions.
- interrogate: Measures docstring coverage across your codebase, helping you track progress toward 100% coverage.
These tools focus on structural aspects—syntax, completeness, and style compliance. But what about the quality of the English prose inside the docstrings? Grammar mistakes, unclear phrasing, or inconsistent terminology can undermine even the most well-formatted docstring. For that, consider a proofreading tool like Lint, which checks your docstring text for grammar, spelling, and readability issues, much like a grammar checker for your code comments. While Lint isn't a docstring syntax validator, it complements tools like pydocstyle by ensuring the human-readable parts are just as polished as the structure.
Practical Tips for Effective Docstrings
Regardless of style, follow these best practices to make your docstrings genuinely useful:
Conclusion
Mastering Python docstring writing is a valuable skill that pays off in maintainability, collaboration, and automated documentation. Whether you prefer the clean Google style, the structured NumPy format, or the powerful reST directives, the key is to choose one and enforce it consistently. Use tools like pydocstyle and flake8-docstrings for structural validation, and consider a prose checker like Lint to polish the English text. With these practices and tools, your docstrings will be as robust as your code.
📌 Prices and tool count in this article may be outdated. Lint now ships 16 tools with Pro at $12/mo, or $39/year founding. See the current pricing page.
Stop letting Grammarly break your code
18 AI and browser tools built for developers. Code-aware parsing.
Or upgrade to Pro for 500 checks a day · All tools · No ads