Python: Docstrings

In Python, a docstring is a short message you write inside your code to explain what something does. It stands for documentation string. You place it right below a function, class, or module — inside triple quotes ("""like this""").

Docstrings are not comments. They are part of your code and can be seen when someone uses the help() function. This means other people (and even your future self) can quickly understand what your code does without reading every line.

Why use docstrings?

Because clear code is kind code. If you share your work, or come back to it months later, a good docstring saves time, confusion, and headaches. It makes your function feel like a friendly tool instead of a mystery box.

Here’s a simple example:

def bark():
    """Make the dog bark loudly."""
    print("Woof! Woof!")


help(bark)

Now when someone types help(bark), they’ll know exactly what it does. And honestly, who wouldn’t want to hear a dog bark in Python?

Docstrings

How to Write a Simple One-Line Docstring

A one-line docstring is the quickest way to describe what a function, method, or class does — all in one clean sentence. It’s short, straight to the point, and easy to read.

Format Rules:

  • Use triple double-quotes: """Your message here."""
  • Place the docstring immediately below the function header.
  • Start with a capital letter and end with a period.
  • Keep it all on one line.

This kind of docstring is best when your function is small and simple — like a helper that adds numbers, prints a message, or plays a sound.

def chase_cat():
    """Dog chases a cat across the garden."""

    return "Zoom!"

This tells us exactly what the function does — no guessing, no digging through the code. One-liners like this are perfect for short, clear actions where extra details aren’t needed.

Use one-line docstrings often, and your code will feel like it’s telling you what it’s doing — like a well-trained pup following your lead.

Writing Multi-line Docstrings

There are times when a single line isn’t enough to explain what your function does. If your function accepts arguments, returns something important, or needs extra explanation, a multi-line docstring is the way to go. These docstrings give you more room to describe how everything works in a clean and structured format.

A well-written multi-line docstring begins with a short summary of the function’s purpose. This is followed by a more detailed explanation of the input parameters and what the function returns. If needed, you can also include notes or tips at the end, such as special instructions or warnings. Leave a blank line between the summary and the rest of the content to keep the docstring readable.

Here’s an example of a fun, well-structured multi-line docstring:

def fly_to_mars(speed):
    """
    Launches a rocket to Mars.

    Args:
        speed (int): Speed in km/h.

    Returns:
        str: Countdown message.

    Note:
        Don’t forget your spacesuit!
    """

    return "3...2...1...Blast off!"

This docstring tells us exactly what the function does, what kind of input it expects, and what output it provides. The extra note adds a bit of personality, which makes the code more fun to read and work with. Use multi-line docstrings when your function has more going on than a simple task. They help you write clearer code that others—and your future self—will thank you for.

Describing Arguments and Return Values

When your function takes inputs or produces outputs, your docstring should describe them clearly. This is where the Args and Returns sections come in. They explain what kind of data your function expects, and what it gives back. If your function might raise an error in some situations, you can also include a Raises section to describe that.

In the Args section, list each parameter, its type in parentheses, and a short explanation of what it represents. Keep the language simple and specific. For the Returns section, describe the return value in the same way—what it is, its type, and what it means.

Here’s a fun animal-themed example that uses both sections:

def feed_elephant(food):
    """
    Feeds the elephant its favorite snack.

    Args:
        food (str): Type of food.

    Returns:
        bool: True if the elephant is happy.
    """

    return food.lower() == "bananas"

In this case, the function takes a type of food as input and returns a boolean value—True if the elephant likes the food, and False if it doesn’t. The docstring explains both parts clearly, so anyone using the function knows exactly what to give it and what to expect in return.

Describing your arguments and return values this way makes your code much easier to read, especially for people who didn’t write it. It also helps prevent mistakes when others try to use your functions.

Class and Method Docstrings

Just like functions, classes in Python should have docstrings to explain what they represent and how they are used. A class docstring is placed right below the class definition. It usually gives a short summary of what the class does or models, especially if it represents something complex.

Each method inside a class should also have its own docstring, especially if the method takes arguments or returns values. The structure for method docstrings is the same as for functions: a short summary, followed by sections for Args, Returns, and possibly Raises, depending on what the method does.

Here’s a fun example of a movie-themed class with a method:

class TimeMachine:
    """
    A magical time machine that travels through decades.
    """

    def travel(self, year):
        """
        Travels to the given year.

        Args:
            year (int): The year to travel to.

        Returns:
            str: A greeting from the new time.
        """

        return f"Welcome to the year {year}!"

In this example, the class docstring gives us a quick idea of what the TimeMachine class represents. The method travel() has its own docstring that explains what input it takes and what it returns. This makes the code more readable and easier to use, especially in larger projects where someone might be using your class without knowing how it works inside.

Using docstrings in both your classes and methods keeps your code well-documented and helps others (and yourself) understand how to use your objects properly.

Docstrings for Modules

In Python, you can also write docstrings at the very top of a file—before any imports, code, or classes. These are called module docstrings, and they describe the purpose and contents of the entire file. They help anyone reading or using your module understand what the file is for, what features it includes, and how it might be used.

A module docstring should begin with a short summary of the file’s purpose. After that, you can briefly mention what the module contains—such as key functions, classes, or behaviors. If needed, you can also include a short usage note or example.

Here’s a short and fun example for a Python file that manages animals in a virtual zoo:

"""
zoo.py

This module manages a virtual zoo with feeding, cleaning, and animal games.
"""

This docstring tells us that the file is named zoo.py and explains what kind of tasks the code handles. It sets the tone for the rest of the file and helps readers know what to expect before they dive into the details.

Adding a module-level docstring is a small step that makes a big difference, especially in larger projects with many files. It gives structure, improves clarity, and helps make your codebase more welcoming to others.

Describing Exceptions with Raises

Sometimes, your functions might run into problems—like if someone passes the wrong kind of input or tries to divide by zero. When your function can raise an error on purpose, it’s helpful to say so in the docstring. This is where the Raises section comes in.

Use the Raises section to tell people which exceptions the function might throw, and why. This way, users of your code know what to expect and can handle errors properly in their own code.

Here’s an example where a function feeds a lion but only accepts certain foods. If you try to feed it something dangerous, it raises a ValueError:

def feed_lion(food):
    """
    Feeds the lion if the food is safe.

    Args:
        food (str): The food item to give the lion.

    Returns:
        str: A happy roar if the lion likes it.

    Raises:
        ValueError: If the food is not safe for the lion.
    """

    if food.lower() not in ["meat", "chicken"]:
        raise ValueError("That food is not safe for lions!")

    return "ROAR! Thank you!"

In this example, the Raises section makes it clear that a ValueError can happen, and it explains when and why. This helps users understand the rules and makes your function safer to use.

Always include a Raises section when your function might throw an exception that isn’t obvious. It shows that you’re thinking ahead and writing code that’s both clear and responsible.

How to Use help() with Docstrings

One of the best things about writing good docstrings is that Python makes them easy to access using the built-in help() function. When you call help() on a function, class, or module, Python shows you the docstring you wrote—right there in the terminal or interpreter. This makes your code feel like it’s self-explaining.

You don’t need to import anything special to use help(). Just make sure the function or class you want to inspect is already defined or imported into your current Python session.

Here’s an example using the feed_elephant function from earlier:

def feed_elephant(food):
    """
    Feeds the elephant its favorite snack.

    Args:
        food (str): Type of food.

    Returns:
        bool: True if the elephant is happy.
    """

    return food.lower() == "bananas"

Now, in your Python shell or script, simply type:

help(feed_elephant)

Python will then print out the docstring, showing you the summary, arguments, and return value in a clear and organized way. This makes help() a powerful tool for exploring code—especially when working with someone else’s project or revisiting your own work after a long break.

Docstrings

Writing helpful docstrings means your functions and classes can explain themselves, and help() is the way to listen.

Quick Tips & Style Reminders

When writing docstrings, your goal is clarity—not cleverness. A good docstring is like a helpful guide: it tells you exactly what something does, without making you think too hard. Keep your language simple, direct, and focused on what the function or class is meant to do.

Always write docstrings in the present tense. Say “Returns the result” instead of “Will return” or “Returned.” This matches the style used in most official Python documentation and keeps your writing consistent.

Once you pick a format—whether you’re writing one-liners, multi-line docstrings with Args and Returns, or including Raises—stick with it throughout your project. Mixing styles can make your code harder to follow.

Also, pay attention to indentation and spacing. Docstrings should be indented to match the block they belong to. Inside multi-line docstrings, line up your sections neatly and leave blank lines between the summary and the details. These small touches make your code look polished and professional.

In the end, your docstrings are part of your code’s user experience. A clean, helpful docstring can turn a function into something that feels easy to understand—even magical.

Closing Example: A Mini Docstring Zoo

To wrap things up, here’s a small and cheerful example that brings together everything we’ve covered. This mini “docstring zoo” shows how to use docstrings for a module, a simple function, and a class with a method. The code is fun, easy to read, and quick to copy into your own projects.

Each part includes a clear docstring: the module explains what it’s for, the function describes what it does in one line, and the class has both a class-level and method-level docstring. It’s a short script, but everything is well-documented and easy to understand.

"""
jungle.py

Welcome to the jungle! This module lets animals roar, fly, and more.
"""

def roar(animal):
    """Makes an animal roar."""

    return f"{animal} goes ROAR!"


class Parrot:
    """A colorful bird that repeats what you say."""

    def speak(self, phrase):
        """
        Repeats the given phrase.

        Args:
            phrase (str): The phrase to repeat.

        Returns:
            str: Repeated phrase.
        """

        return f"Polly says: {phrase}"

This example ties everything together: a neat module docstring at the top, clear one-line and multi-line docstrings where needed, and consistent formatting throughout. It shows how writing good docstrings doesn’t have to be boring—it can actually make your code more enjoyable to work with.

Conclusion

Docstrings may seem small, but they carry lasting value. They’re not just for explaining your code to others—they’re also for your future self. One day, you’ll look back at something you wrote months ago and thank yourself for the clear notes.

Whether you’re building a time machine, feeding elephants, or teaching parrots to talk, writing good docstrings makes your code easier to understand, easier to maintain, and much more enjoyable to share. Good docstrings invite others into your world and help them use your work with confidence.

So keep your docstrings clear, short, and helpful. Choose a format and stick to it. Have fun with your examples. And above all, treat your code like a story worth telling—because every line has a role, and every function has something to say.