Python Docstrings

Python docstrings are an essential part of writing clean, readable, and maintainable code. They allow you to document your functions, classes, and modules, making it easier for others (and yourself) to understand the code. Docstrings are enclosed in triple quotes and are placed immediately after the function, class, or module definition.

Here are some common uses of docstrings:

  • Documenting functions: Explain what a function does, its parameters, and its return values.
  • Documenting classes: Provide an overview of the class, its attributes, and methods.
  • Providing module-level documentation: Explain the purpose of a Python module.
  • Generating automated documentation: Tools like Sphinx can generate documentation from docstrings.


What You'll Learn

You will learn the basics of Python docstrings, how to document functions, classes, and modules, and why it's important to include docstrings in your code. By the end of this page, you’ll know how to write clear and concise documentation for your Python code.


Understanding docstrings

In Python, a docstring is a string literal that appears right after a function, class, or module definition. It’s typically used to explain what the function/class/module does, what parameters it takes, and what it returns.

The basic syntax of a docstring looks like this:

python
def my_function():
    """This is a docstring."""
    pass

The docstring is enclosed in triple quotes ("""). For functions and classes, it should be indented to the same level as the code block. Module docstrings are typically placed at the top without indentation.

  • Function docstring: Explains what the function does, its parameters, and return value.
  • Class docstring: Describes the class and its attributes or methods.
  • Module docstring: Describes the module's purpose and any important details for users of the module.

Example 1: Function Docstring

Here’s how to document a simple Python function with a docstring:

python
def greet(name):
    """
    Prints a greeting message to the user.
    
    Parameters:
    name (str): The name of the person to greet.
    
    Returns:
    None
    """
    print("Hello, " + name + "!")

How It Works:

  • """: This is how the docstring starts and ends (triple quotes).
  • Parameters:: A section explaining the function’s parameters.
  • Returns:: A section explaining the return value (if any).
  • The docstring helps other programmers quickly understand what this function does without reading the entire function’s code.

Output

Hello, John!

Example 2: Class Docstring

Here’s an example of documenting a class with a docstring:

python
class Dog:
    """
    A class representing a dog.
    
    Attributes:
    name (str): The dog's name.
    age (int): The dog's age.
    
    Methods:
    bark: Prints a barking sound.
    """
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print("Woof!")

How It Works:

  • """: The docstring explaining the class starts and ends with triple quotes.
  • Attributes:: Lists the key attributes of the class.
  • Methods:: Describes the methods defined in the class.

Example 3: Module Docstring

Here’s how to document a Python module with a docstring:

python
# module_example.py
"""
This module contains functions to perform basic arithmetic operations.
"""
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

How It Works:

  • The module docstring provides an overview of the module's purpose and functionality.

Exercises

Try out the following exercises to practice using docstrings in your Python code.

1. Write a function that calculates the square of a number and add a docstring to it.
python
# Exercise 1: Function to square a number
# Add a docstring explaining the function
def square(num):
    """Returns the square of the number."""
    return num ** 2

2. Write a function that reverses a string and include a docstring explaining what it does.
python
# Exercise 3: Function to reverse a string
# Add a docstring explaining the function
def reverse_string(s):
    """
    Reverses the given string.

    Parameters:
    s (str): The string to reverse.

    Returns:
    str: The reversed string.
    """
    return s[::-1]


Frequently Asked Questions

What is a docstring in Python?

A docstring is a string literal used to document a function, class, or module. It appears immediately after the definition and explains the purpose and usage of the code block.


How do you write a docstring?

Write a docstring by placing triple quotes (""") directly below the function, class, or module header. Inside the quotes, describe what the code does, its parameters, and return values.


What is the difference between comments and docstrings?

Comments use the # symbol and are ignored by Python at runtime. Docstrings are string literals accessible via the help() function or .__doc__ attribute.


Can docstrings be multiline?

Absolutely! Multiline docstrings are ideal for detailed documentation and follow a consistent format using triple quotes, often covering parameters, return types, and examples.


Are docstrings required in Python?

They’re not mandatory, but they’re a best practice. Including docstrings improves code readability, helps others understand your code, and enables tools to auto-generate documentation.



What's Next?

Next, you'll dive into Python modules, which allow you to organize your code into separate files and reuse functionality across different programs. You'll learn how to import built-in modules, create your own, and explore the power of modular programming for cleaner and more maintainable code.