Python
docstring
function
programming
code documentation

Getting the docstring from a function

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Every Python function can have a docstring — a string literal as the first statement in the function body. Python stores this string in the function's __doc__ attribute, making it accessible at runtime. You can retrieve a function's docstring with function.__doc__, format it with inspect.getdoc(), or use help() for interactive viewing. Docstrings power Python's built-in help system, IDE tooltips, and documentation generators like Sphinx.

Accessing with doc

python
1def calculate_area(radius):
2    """Calculate the area of a circle given its radius.
3
4    Args:
5        radius: The radius of the circle (must be non-negative).
6
7    Returns:
8        The area as a float.
9
10    Raises:
11        ValueError: If radius is negative.
12    """
13    if radius < 0:
14        raise ValueError("Radius cannot be negative")
15    return 3.14159 * radius ** 2
16
17# Access the docstring
18print(calculate_area.__doc__)

Output (preserves original whitespace):

 
1Calculate the area of a circle given its radius.
2
3    Args:
4        radius: The radius of the circle (must be non-negative).
5
6    Returns:
7        The area as a float.
8
9    Raises:
10        ValueError: If radius is negative.

__doc__ returns the raw string with original indentation intact.

Cleaned Docstring with inspect.getdoc()

python
import inspect

print(inspect.getdoc(calculate_area))

Output (indentation cleaned up):

 
1Calculate the area of a circle given its radius.
2
3Args:
4    radius: The radius of the circle (must be non-negative).
5
6Returns:
7    The area as a float.
8
9Raises:
10    ValueError: If radius is negative.

inspect.getdoc() strips leading whitespace from all lines and trims blank lines at the start and end. This gives you the docstring as it was intended to be read.

Using help()

python
help(calculate_area)

Output:

 
1Help on function calculate_area in module __main__:
2
3calculate_area(radius)
4    Calculate the area of a circle given its radius.
5
6    Args:
7        radius: The radius of the circle (must be non-negative).
8
9    Returns:
10        The area as a float.
11
12    Raises:
13        ValueError: If radius is negative.

help() shows the function signature alongside the docstring. It is designed for interactive exploration in the REPL.

Docstrings on Methods and Classes

python
1class Circle:
2    """A circle defined by its radius.
3
4    Attributes:
5        radius: The radius of the circle.
6    """
7
8    def __init__(self, radius):
9        """Initialize a Circle with the given radius."""
10        self.radius = radius
11
12    def area(self):
13        """Return the area of the circle."""
14        return 3.14159 * self.radius ** 2
15
16# Class docstring
17print(Circle.__doc__)
18# A circle defined by its radius. ...
19
20# Method docstrings
21print(Circle.__init__.__doc__)
22# Initialize a Circle with the given radius.
23
24print(Circle.area.__doc__)
25# Return the area of the circle.
26
27# Or use inspect for cleaner output
28import inspect
29print(inspect.getdoc(Circle))

Docstrings on Modules

A module's docstring is the first string literal in the file:

python
1# mymodule.py
2"""Utility functions for geometric calculations.
3
4This module provides functions for computing areas, volumes,
5and perimeters of common shapes.
6"""
7
8def area_rectangle(w, h):
9    """Return the area of a rectangle."""
10    return w * h
python
import mymodule
print(mymodule.__doc__)
# Utility functions for geometric calculations. ...

Functions Without Docstrings

python
1def add(a, b):
2    return a + b
3
4print(add.__doc__)     # None
5print(type(add.__doc__))  # <class 'NoneType'>
6
7import inspect
8print(inspect.getdoc(add))  # None

If a function has no docstring, __doc__ is None. Always check for None before processing.

Docstring Styles

Python has three common docstring conventions:

python
1# Google style
2def fetch(url, timeout=30):
3    """Fetch content from a URL.
4
5    Args:
6        url: The URL to fetch.
7        timeout: Request timeout in seconds.
8
9    Returns:
10        The response body as a string.
11
12    Raises:
13        ConnectionError: If the URL is unreachable.
14    """
15
16# NumPy/SciPy style
17def fetch(url, timeout=30):
18    """Fetch content from a URL.
19
20    Parameters
21    ----------
22    url : str
23        The URL to fetch.
24    timeout : int, optional
25        Request timeout in seconds (default 30).
26
27    Returns
28    -------
29    str
30        The response body.
31    """
32
33# Sphinx (reStructuredText) style
34def fetch(url, timeout=30):
35    """Fetch content from a URL.
36
37    :param url: The URL to fetch.
38    :type url: str
39    :param timeout: Request timeout in seconds.
40    :type timeout: int
41    :returns: The response body.
42    :rtype: str
43    :raises ConnectionError: If the URL is unreachable.
44    """

All three are stored the same way in __doc__ — the style only matters for documentation generators.

Programmatic Docstring Inspection

python
1import inspect
2
3def summarize_function(func):
4    """Print a function's name, signature, and docstring."""
5    sig = inspect.signature(func)
6    doc = inspect.getdoc(func) or "No documentation available"
7    first_line = doc.split("\n")[0]
8
9    print(f"{func.__name__}{sig}")
10    print(f"  {first_line}")
11
12# Use it
13summarize_function(calculate_area)
14# calculate_area(radius)
15#   Calculate the area of a circle given its radius.

This pattern is useful for building custom help systems, API documentation, or command-line tool --help output.

Decorators and Docstrings

Decorators can accidentally overwrite a function's docstring:

python
1def log_calls(func):
2    def wrapper(*args, **kwargs):
3        print(f"Calling {func.__name__}")
4        return func(*args, **kwargs)
5    return wrapper
6
7@log_calls
8def greet(name):
9    """Greet a person by name."""
10    return f"Hello, {name}!"
11
12print(greet.__doc__)   # None — the wrapper's docstring, not greet's
13print(greet.__name__)  # wrapper — not greet

Fix with functools.wraps:

python
1from functools import wraps
2
3def log_calls(func):
4    @wraps(func)  # Copies __doc__, __name__, __module__, etc.
5    def wrapper(*args, **kwargs):
6        print(f"Calling {func.__name__}")
7        return func(*args, **kwargs)
8    return wrapper
9
10@log_calls
11def greet(name):
12    """Greet a person by name."""
13    return f"Hello, {name}!"
14
15print(greet.__doc__)   # Greet a person by name.
16print(greet.__name__)  # greet

Always use @functools.wraps in decorators to preserve the wrapped function's metadata.

Common Pitfalls

  • Confusing comments with docstrings: A # comment above or inside a function is not a docstring. The docstring must be a string literal as the first statement in the body.
  • Forgetting functools.wraps in decorators: Decorators replace the function object. Without @wraps, __doc__, __name__, and other attributes are lost.
  • Raw __doc__ has extra whitespace: Use inspect.getdoc() for cleaned output. Raw __doc__ preserves the indentation from the source code.
  • Docstring is None: Functions without a docstring literal have __doc__ = None. Check for None before calling .split() or other string methods on it.
  • help() in scripts vs REPL: help() uses a pager in interactive mode but prints directly when piped or in a script. For programmatic use, access __doc__ directly.

Summary

  • Access a function's docstring with func.__doc__ (raw) or inspect.getdoc(func) (cleaned)
  • Use help(func) for interactive viewing with signature and formatting
  • Docstrings work on functions, methods, classes, and modules
  • __doc__ is None if no docstring is defined
  • Use @functools.wraps in decorators to preserve the wrapped function's docstring
  • Choose a consistent style (Google, NumPy, or Sphinx) for documentation generators

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.