Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is docstring in Python

Understanding Docstrings: The Basics

When you're starting out as a programmer, it's like learning a new language. You need to know how to write 'sentences' (which we call code) that the computer understands. As you learn, you'll also discover that it's just as important to write notes to yourself and other programmers to explain what your code is doing. In Python, these notes are called "docstrings."

Docstrings are short for "documentation strings." They are a way to document your code right where it lives: in the code itself. Think of them as a handy note or a guidebook that tells you or anyone else looking at your code what a particular piece of code is supposed to do.

Writing Your First Docstring

To write a docstring, you simply start with a triple quote, write your explanation, and then end with another triple quote. Here's the simplest example:

def greet(name):
    """
    This function greets the person whose name is passed in as a parameter.
    """
    print(f"Hello, {name}!")

In this snippet, the text between the triple quotes is the docstring for the greet function. It explains that the function's purpose is to print a greeting for the person named in the parameter.

The Why and How of Docstrings

You might wonder why you should bother writing these notes. The answer is simple: clarity. Just as it's easier to assemble furniture with instructions, it's easier to understand and use code when it comes with explanations. Docstrings are especially useful when someone else is trying to use your code. They can read the docstring to understand what a function does without having to decipher the code itself.

Docstrings are not just for functions, though. You can (and should) write docstrings for modules, classes, and methods too:

class Greeter:
    """
    A class to create a greeter object that can greet people.
    """

    def __init__(self, name):
        """
        The constructor for Greeter class.

        Parameters:
           name (str): The name of the person to greet.
        """
        self.name = name

    def greet(self):
        """
        The method to print a greeting message.
        """
        print(f"Hello, {self.name}!")

In this example, each part of the code has its own docstring explaining what it does.

Going Beyond the Basics

Docstrings can also include more detailed information, like what parameters a function takes, what it returns, and any errors it might raise. This is where you can get a little more technical, but remember, the goal is to be helpful, not overwhelming.

Here's a more detailed docstring for our greet function:

def greet(name):
    """
    Greets a person with their name.

    Parameters:
    name (str): The name of the person to greet.

    Returns:
    None
    """
    print(f"Hello, {name}!")

In this docstring, we've added sections for "Parameters" and "Returns." The "Parameters" section explains what inputs the function expects, and the "Returns" section tells us what the function gives back when it's done. In this case, it doesn't return anything, which we denote with None.

The Intuition Behind Docstrings

Think of docstrings as the recipe for a dish. The recipe tells you what ingredients you need, how to put them together, and what to expect as the final product. Similarly, a docstring tells you what inputs a function needs, what it does with those inputs, and what you will get after the function is executed.

Just like how a good recipe is clear and easy to follow, a good docstring should be easy to read and understand. It's not just about documenting every little detail but about providing the necessary information in a clear and concise way.

Best Practices for Writing Docstrings

When writing docstrings, it's good to follow some best practices:

  • Be concise but informative: Your docstring should be brief but detailed enough to give a clear understanding of the code's purpose.
  • Follow a convention: There are several docstring conventions like Google style, NumPy/SciPy style, and reStructuredText style. Pick one and be consistent with it.
  • Include all necessary information: Mention the purpose, parameters, return values, and any exceptions raised.
  • Keep it up to date: If you change your code, make sure to update the docstring to match.

Docstrings and Python's Help System

One of the cool things about docstrings is that they're not just notes that sit there in the code. Python actually uses them as part of its built-in help system. If you've ever used the help() function in Python, you've seen docstrings in action. When you call help() on a function, class, or module, Python displays its docstring.

Let's see this with our greet function:

help(greet)

When you run this command, Python will print out the docstring for the greet function, telling you exactly what it does and how to use it.

The Analogy of Docstrings

If you're still wrapping your head around docstrings, here's an analogy that might help. Imagine you've just bought a new gadget, but it came without any instructions. You'd have to figure out how it works through trial and error, and you might even use it wrong or break it. Now, imagine that same gadget comes with a clear, concise manual that explains everything you need to know. That manual is like a docstring in your code. It guides you and anyone else who uses your code, preventing confusion and mistakes.

Conclusion

Docstrings are the guiding light in the sometimes dark and mysterious world of code. They help us understand what a piece of code is meant to do, how to use it, and what to expect from it. As a beginner, you might be tempted to skip writing docstrings, but taking the time to include them will make your journey as a programmer much smoother. They're a simple tool, but they pack a powerful punch in terms of making your code more accessible and maintainable.

In the end, writing good docstrings is a bit like planting a tree. You might not need its shade today, but one day, you or someone else will be grateful for the foresight. So, as you continue to learn and grow in your programming skills, remember to document your code with thoughtful, helpful docstrings. Happy coding!