Blog Post #99: Documenting Your Code: The Power of Docstrings

As we write more functions, our programs become more complex. While our code might make perfect sense to us the moment we write it, it can be nearly incomprehensible to others—or even to ourselves six months from now. Good code is not just code that works; it’s code that is understandable.

In this post, we’re going to learn about a crucial tool for creating understandable code: docstrings. These are a formal way to document what your functions do, making them easier to use and maintain.

Comments vs. Docstrings

In Post #7, we learned about comments (#), which are great for explaining the “how” or “why” of a tricky line of code for someone who is reading the source.

Docstrings, on the other hand, explain the “what” of a function, module, or class. They are a user manual for your code, describing its purpose, what data it needs, and what it returns.

A simple way to think about it is:

  • Comments are for maintainers of the code.
  • Docstrings are for users of the code.

How to Write a Docstring

A docstring is a string literal that occurs as the very first statement in a function’s body. By convention, they are created using triple double quotes (""").

While there are many official styles, a good, simple docstring generally includes:

  1. A brief, one-line summary of what the function does.
  2. (Optional) A more detailed description.
  3. An Args: section describing each parameter the function accepts.
  4. A Returns: section describing the value the function returns.

Let’s write a function with a complete docstring.

def calculate_rectangle_area(length, width):
    """Calculate the area of a rectangle.

    This function takes the length and width of a rectangle and
    returns its calculated area.

    Args:
        length (int or float): The length of the rectangle.
        width (int or float): The width of the rectangle.

    Returns:
        int or float: The calculated area of the rectangle.
    """
    if length <= 0 or width <= 0:
        return 0
    return length * width

The Magic of Docstrings: help()

So why go to all this trouble instead of just using a big # comment? Because docstrings are a special attribute of the function itself, and Python’s built-in tools can automatically access them.

The most important of these is the help() function. If you pass your own function to help(), it will find the docstring and print a nicely formatted help page for you.

Let’s try it with the function we just created:

# You can run this in an interactive Python session or in a script
help(calculate_rectangle_area)

The output will be:

Help on function calculate_rectangle_area in module __main__:

calculate_rectangle_area(length, width)
    Calculate the area of a rectangle.
    
    This function takes the length and width of a rectangle and
    returns its calculated area.
    
    Args:
        length (int or float): The length of the rectangle.
        width (int or float): The width of the rectangle.
    
    Returns:
        int or float: The calculated area of the rectangle.

This is incredibly powerful. By writing good docstrings, you are creating a built-in user manual for your own code that anyone (including you) can access at any time.

What’s Next?

Writing docstrings is a hallmark of a professional Python developer. It makes your code more usable, maintainable, and easier for others to understand. Get in the habit of writing a docstring for every function you create.

In our docstring example, we informally mentioned the expected types of our parameters, like (int or float). While this is helpful for human readers, modern Python provides a formal way to declare these types directly in the function signature. This is called type hinting. In Post #100, we’ll get a glimpse into this professional coding feature.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment