How to Write Docstrings in Python

How to Write Docstrings in Python

Writing clear, consistent docstrings in Python helps others understand your code’s purpose, parameters, and outputs. In this guide on how to write docstrings in Python, you’ll learn about best practices, standard formats, and common pitfalls to avoid, ensuring your documentation is accessible to users and tools alike.

By the end of this tutorial, you’ll understand that:

  • Docstrings are strings used to document your Python code and can be accessed at runtime.
  • Python comments and docstrings have important differences.
  • One-line and multiline docstrings are classifications of docstrings.
  • Common docstring formats include reStructuredText, Google-style, NumPy-style, and doctest-style.
  • Antipatterns such as inconsistent formatting should be avoided when writing docstrings.

Explore the following sections to see concrete examples and detailed explanations for crafting effective docstrings in your Python projects.

Take the Quiz: Test your knowledge with our interactive “How to Write Docstrings in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Write Docstrings in Python

Test your knowledge of Python docstrings, including syntax, conventions, formats, and how to access and generate documentation.

Getting Started With Docstrings in Python

Python docstrings are string literals that show information regarding Python functions, classes, methods, and modules, allowing them to be properly documented. They are placed immediately after the definition line in triple double quotes (""").

Their use and convention are described in PEP 257, which is a Python Enhancement Proposal (PEP) that outlines conventions for writing docstrings. Docstrings don’t follow a strict formal style. Here’s an example:

Python docstring_format.py
def determine_magic_level(magic_number):
    """
    Multiply a wizard's favorite number by 3 to reveal their magic level.
    """
    return magic_number * 3

Docstrings are a built-in means of documentation. While this may remind you of comments in Python, docstrings serve a distinct purpose. If you’re curious and would like to see a quick breakdown of the differences now, open the collapsible section below.

Python comments and docstrings seem a lot alike, but they’re actually quite different in a number of ways because they serve different purposes:

Comments Docstrings
Begin with # Are enclosed in triple quotes (""")
Consist of notes and reminders written by developers for other developers Provide documentation for users and tools
Are ignored by the Python interpreter Are stored in .__doc__ and accessible at runtime
Can be placed anywhere in code Are placed at the start of modules, classes, and functions

To summarize, comments explain parts of an implementation that may not be obvious or that record important notes for other developers. Docstrings describe modules, classes, and functions so users and tools can access that information at runtime.

So, while comments and docstrings may look similar at first glance, their purpose and behavior in Python are different. Next, you’ll look at one-line and multiline docstrings.

One-Line vs Multiline Docstrings

Docstrings are generally classified as either one-line or multiline. As the names suggest, one-line docstrings take up only a single line, while multiline docstrings span more than one line. While this may appear to be a slight difference, how you use and format them in your code matters.

An important formatting rule from PEP 257 is that one-line docstrings should be concise, while multiline docstrings should have their closing quotes on a new line. You may resort to a one-line docstring for relatively straightforward programs like the one below:

Python one_line_docstring.py
import random

def picking_hat():
    """Return a random house name."""
    houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
    return random.choice(houses)

In this example, you see a program that returns a random house as depicted in the classic Harry Potter stories. This is a good example for the use of one-line docstrings.

You use multiline docstrings when you have to provide a more thorough explanation of your code, which is helpful for other developers. Generally, a docstring should contain parameters, return value details, and a summary of the code.

You’re free to format docstrings as you like. That being said, you’ll learn later that there are common docstring formats that you may follow. Here’s an example of a multiline docstring:

Python multiline_docstring.py
def get_harry_potter_book(publication_year, title):
    """
    Retrieve a Harry Potter book by its publication year and name.

    Parameters:
    publication_year (int): The year the book was published.
    title (str): The title of the book.

    Returns:
    str: A sentence describing the book and its publication year.
    """
    return f"The book {title!r} was published in the year {publication_year}."

As you can see, the closing quotes for this multiline docstring appear on a separate line. Now that you understand the difference between one-line and multiline docstrings, you’ll learn how to access docstrings in your code.

Ways to Access Docstrings in Python

Unlike code comments, docstrings aren’t ignored by the interpreter. They become a part of the program and serve as associated documentation for anyone who wants to understand your program and what it does. That’s why knowing how to access docstrings is so useful. Python provides two built-in ways to access docstrings: the .__doc__ attribute and the help() function.

The .__doc__ Attribute

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

Locked learning resources

The full article is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

About Amanda Adoyi

Amanda is a Software Developer, writer and all-round nerd who loves to tinker with code and build projects in her free time. She also goes by Lonercode.

» More about Amanda

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Become a Member to join the conversation.

Keep Learning

Related Topics: basics best-practices