Skip to main content

How to Document Functions Properly in Python

Documentation is a critical aspect of writing maintainable Python code. Docstrings (documentation strings) allow you to embed documentation directly into your functions, classes, and modules. Unlike comments, which are ignored by the interpreter, docstrings are retained at runtime and can be accessed programmatically.

This guide explains how to access existing documentation and how to write professional docstrings for your own functions.

Accessing Existing Documentation

Before writing your own, it is useful to understand how to read documentation for built-in Python functions. Python provides two primary ways to do this: the help() function and the __doc__ attribute.

Using the help() Function

The help() function provides an interactive, formatted view of the documentation. It is best used in the Python shell.

# ✅ Correct: Using help() to view formatted documentation
help(print)

Output (truncated):

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
...

Using the __doc__ Attribute

Every Python object has a __doc__ attribute that contains the raw documentation string. This is useful if you want to access the text programmatically within a script.

# ✅ Correct: Accessing the raw docstring string
print(len.__doc__)

Output:

Return the number of items in a container.
note

help() formats the text and adds metadata (like the function signature), whereas __doc__ returns the exact string literal defined in the source code.

Writing Custom Docstrings

To document your own function, you place a string literal immediately after the function definition line (def ...:).

The Wrong Way (Using Comments)

Standard hash comments (#) are for developers reading the source code. They are not accessible via help().

def greet(name):
# ⛔️ Incorrect: This is a comment, not a docstring.
# It will not appear in help(greet).
print(f"Hello, {name}!")

print(greet.__doc__)

Output:

None

The Right Way (Triple Quotes)

Use triple quotes (""") to define multi-line docstrings. A common convention (used by Google and others) is to list arguments (Args) and return values.

def greet(name, greeting="Hello"):
"""
Greets a person with a given message.

Args:
name (str): The name of the person to greet.
greeting (str, optional): The greeting message. Defaults to "Hello".
"""
print(f"{greeting}, {name}!")

# ✅ Correct: The docstring is now part of the function object
print(greet.__doc__)

Output:

    Greets a person with a given message.

Args:
name (str): The name of the person to greet.
greeting (str, optional): The greeting message. Defaults to "Hello".
tip

Always indent your docstring to match the indentation level of the function body. Python handles the indentation parsing automatically when displaying it via help().

Verifying Your Documentation

Once you have defined your function with a docstring, you can verify it using the tools discussed in Section 1. This ensures that other developers (or you in the future) can understand your code without reading the internal logic.

from my_function import greet

# ✅ Check the interactive help page
help(greet)

Output:

Help on function greet in module my_function:

greet(name, greeting='Hello')
Greets a person with a given message.

Args:
name (str): The name of the person to greet.
greeting (str, optional): The greeting message. Defaults to "Hello".

Conclusion

Docstrings are an essential part of professional Python programming.

  1. Use help(obj) to read formatted documentation interactively.
  2. Use obj.__doc__ to access the raw documentation string programmatically.
  3. Define Docstrings using triple quotes (""") immediately after the def line.
  4. Structure your docstrings to include a summary, arguments, and return values.