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.
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.
print(len.__doc__)Output:
Return the number of items in a container.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):
print(f"Hello, {name}!")
print(greet.__doc__)Output:
NoneThe 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}!")
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".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
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.
- Use
help(obj)to read formatted documentation interactively. - Use
obj.__doc__to access the raw documentation string programmatically. - Define Docstrings using triple quotes (
""") immediately after thedefline. - Structure your docstrings to include a summary, arguments, and return values.