Writing Effective Docstrings for Data Science Functions
Good docstrings are essential in data science projects. They serve as documentation, improve code readability, help with IDE autocompletion, and make your functions usable by other team members. In 2026, following a consistent docstring style is a key professional practice.
TL;DR — Recommended Docstring Style
- Use Google Style or NumPy Style (Google is more popular in data science)
- Always include
Args,Returns, andExamplessections - Keep docstrings clear, concise, and informative
1. Google Style Docstring (Recommended for Data Science)
import pandas as pd
def analyze_customer_segment(
df: pd.DataFrame,
segment_column: str,
value_column: str = "amount",
min_transactions: int = 5
) -> pd.DataFrame:
"""
Analyze customer behavior by segment and return summary statistics.
This function groups customers by a specified segment column and calculates
key metrics such as total spend, average order value, and transaction count.
Args:
df: Input DataFrame containing customer transaction data.
segment_column: Column name to group customers by (e.g., 'region', 'category').
value_column: Column containing the monetary value (default: 'amount').
min_transactions: Minimum number of transactions required to include a segment.
Returns:
A DataFrame with summary statistics per segment including:
- total_sales
- avg_order_value
- transaction_count
- unique_customers
Raises:
ValueError: If the segment_column or value_column does not exist in df.
Example:
>>> result = analyze_customer_segment(df, "region")
>>> print(result.head())
"""
# Function implementation...
pass
2. Best Practices for Data Science Docstrings 2026
- Always start with a clear, concise one-sentence summary
- Use the Google Style format (most common in data science teams)
- Include
Args,Returns, and optionallyRaisesandExamplesections - Document data types using type hints in the signature and again in the docstring
- Include a short usage example when the function is complex
- Keep docstrings up-to-date when modifying function behavior
What a Docstring Should Contain
A docstring is the string literal on the first line of a function body. Tools such as help(), IDEs and documentation generators read it, so it is the official description of the function.
A useful data science docstring has a one-line summary, then sections for parameters, return value, raised errors and a short example. NumPy and Google styles are both common; pick one and use it consistently across a project.
Worked Example: A NumPy-Style Docstring
The function below documents its inputs and output, and help() can display it.
import pandas as pd
def growth_rate(series: pd.Series, periods: int = 1) -> pd.Series:
"""Compute percentage growth between observations.
Parameters
----------
series : pd.Series
Numeric values in time order.
periods : int, default 1
Number of observations to look back.
Returns
-------
pd.Series
Growth in percent; the first values are NaN.
"""
return series.pct_change(periods=periods) * 100
print(growth_rate(pd.Series([100, 110, 121])).round(1).tolist())
print(growth_rate.__doc__.splitlines()[0])
The first growth value is NaN, as the docstring promises, followed by two 10 percent increases. Printing the first line of __doc__ shows the summary that tools display.
Practical Tips
Examples in docstrings are especially valuable. Written in the doctest format with >>> prompts, they can be executed by python -m doctest, so the documentation also acts as a test and warns you when behaviour changes.
Keep docstrings focused on what the function does and how to use it. Implementation notes, such as why a particular algorithm was chosen, usually belong in comments inside the body, where they sit next to the code they explain.
Finally, mention units and assumptions explicitly. A note such as "prices in USD, one row per order" prevents misuse far more effectively than a long description of the implementation.
Common Mistakes
- Repeating the function name instead of explaining behaviour.
- Leaving docstrings out of date after code changes.
- Omitting units and expected input shapes.
- Using comments above the function instead of a docstring.
Quick Summary
- Start with a one-line summary.
- Document parameters, returns and errors.
- Use one style across a project.
- Keep docstrings in sync with the code.
Conclusion
Well-written docstrings are a hallmark of professional data science code. In 2026, investing time in clear, structured docstrings (especially using Google Style) significantly improves collaboration, maintainability, and the overall quality of your data science projects. A good docstring saves time for both you and your teammates.
Next steps:
- Review your existing data science functions and improve their docstrings using the Google Style format shown above