Docstrings are the built-in way to document Python functions, classes, methods, and modules. A docstring is a string literal that appears as the first statement inside the object’s definition — and it becomes accessible via the __doc__ attribute or help(). Good docstrings make code self-explanatory, improve IDE tooltips, power auto-generated documentation (Sphinx, mkdocs), and help tools like mypy and type checkers.
In 2026, docstrings are non-optional in professional Python — they use type hints, follow standard styles (Google or NumPy), and are concise yet complete. Here’s a practical guide to writing great docstrings.
1. Basic Docstring (One-Line)
def add_numbers(x: int, y: int) -> int:
"""Return the sum of two integers."""
return x + y
print(add_numbers.__doc__) # Return the sum of two integers.
print(help(add_numbers)) # Shows the docstring in help format
2. Multi-Line Docstring (Recommended for Most Functions)
Use triple quotes (""") immediately after the def line. Include description, args, returns, raises, and examples.
def safe_divide(a: float, b: float, /, *, round_digits: int = 2) -> float:
"""
Divide two numbers safely with configurable rounding.
Args:
a: Numerator (must be float or int)
b: Denominator (must be float or int, cannot be zero)
round_digits: Number of decimal places to round to (default 2)
Returns:
The rounded quotient as a float
Raises:
ZeroDivisionError: If b is zero
TypeError: If a or b are not numeric
Examples:
>>> safe_divide(10, 3)
3.33
>>> safe_divide(10, 3, round_digits=4)
3.3333
"""
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")
return round(a / b, round_digits)
3. Popular Docstring Styles (2026 Standards)
Google Style (clean, concise, great for Sphinx/readthedocs)
def calculate_total(items: list[float], discount: float = 0.0) -> float:
"""Calculate total price after discount.
Args:
items: List of item prices
discount: Discount percentage (0.0 to 1.0)
Returns:
Final total amount rounded to 2 decimal places
Raises:
ValueError: If discount is negative or >1.0
"""
...
NumPy Style (detailed, excellent for scientific libraries)
def safe_divide(a, b, round_digits=2):
"""
Safely divide two numbers with rounding.
Parameters
----------
a : float or int
Numerator
b : float or int
Denominator (non-zero)
round_digits : int, optional
Decimal places for rounding (default is 2)
Returns
-------
float
Rounded quotient
Raises
------
ZeroDivisionError
If b is zero
"""
...
4. Accessing & Using Docstrings
# Access via __doc__
print(add_numbers.__doc__)
,[object Object],
,[object Object],
,[object Object],
,[object Object],