Documentation Strings (Docstrings) in Python

A Documentation String (or Docstring) is a special type of comment used in Python to explain what a specific function, class, module, or method does. Unlike regular comments, docstrings are retained by Python at runtime, making them highly valuable for code maintenance and auto - generation of documentation.

Key Rules for Writing Docstrings

To write clean and Pythonic docstrings, you must follow the official PEP 257 guidelines. If these rules are broken, tools like Sphinx cannot auto-generate your documentation properly.
1. Mandatory Triple Quotes : Always enclose docstrings inside triple double quotes """...""". Never use single quotes # or regular strings '...' or "...".
2. Exact Immediate Placement : Place the docstring on the very first line inside a module, class, or function definition.
3. Imperative Mood Verb : Begin the summary phrase with a commanding verb. Write """Return the total.""" instead of """Returns the total.""" or """Returning the total.""".
4. The Blank Line Gap : For multi-line docstrings, always keep one blank line empty between the first summary line and the rest of the detailed text.
5. Closing Quote Position : In a multi-line docstring, the closing triple quotes """ must sit alone on a completely fresh line.
6. Runtime Accessibility : Do not confuse them with comments. Docstrings are stored in memory and must be readable using the __doc__ attribute or help() function.

Types of Docstrings

Python classifies docstrings into two structural types based on the complexity of the code block they explain.

1. One-line Docstrings

Used strictly for very obvious, simple functions or methods where a single sentence is enough to explain the purpose.
RuleThe opening quotes, the summary text, and the closing quotes must all fit on one single line.

def get_user_id(username):
    """Fetch the unique database ID for a given user."""
    return database.lookup(username)

2. Multi-line Docstrings

Used for complex functions, classes, or modules that accept multiple parameters, raise errors, or return specific data structures.
Rule It starts with a brief one-line summary, followed by a blank line, followed by a deeper explanation of arguments and return types.

def connect_to_server(ip_address, port):
    """Establish a secure network connection to the target server.

    This function initializes a socket connection, performs a handshake 
    protocol, and authenticates the client session with the host.

    Parameters:
    ip_address (str): The valid IPv4 or IPv6 address of the server.
    port (int): The network port number (typically 80 or 443).

    Returns:
    bool: True if connection succeeds, False otherwise.
    """
    return socket.open(ip_address, port)

Docstrings vs. Regular Comments

Feature Regular Comments (#) Docstrings (""")
Purpose Explains how a specific line of code works internally. Explains what a function/class does for someone using it.
Runtime Access Ignored completely by the Python interpreter. Saved in memory and accessible via code or IDEs.
Position Can be placed anywhere in the code. Must be the first statement inside the block.